Tuesday, October 30, 2007

Create Datagrid with RowSpan

In some applications we need to create Datagrid to rowspan. But Datagrid doesn't support this feature directly. Following code will create a DataGrid with RowSpan when Values in the First Column (Cell) are same. NOTE: Datasource Should be Sorted with Field you are using RowSpan.

Please Set DataGrid's OnItemDataBound Event to Following function. For the Gridview set Rowdatabound event.

protected void grd1_ItemCreated(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
TableCell preCell = null; // Last Row Cell

if (e.Item.ItemIndex > 0)
{
preCell = grd1.Items[e.Item.ItemIndex - 1].Cells[0];
}

if (preCell != null) // Our logic make sense when last row has any Cells!
{
TableCell cell = e.Item.Cells[0]; // Current Row Cell
if (preCell.Text == cell.Text)
{
if (preCell.Visible == false) // Row Span is already Started ....
{
//currentKeyCell contains current Key value Cell.
currentKeyCell.RowSpan = (currentKeyCell.RowSpan == 0 ? 1 : currentKeyCell.RowSpan) + 1;
}
else
{
//Set Last row Cell's RowSpan ..
preCell.RowSpan = (preCell.RowSpan == 0 ? 1 : preCell.RowSpan) + 1;
//Set New Key value Cell
currentKeyCell = preCell;
}

// Set Current Row Cell Visibility to false.
cell.Visible = false;
}
}
}
}

TableCell currentKeyCell; // Current Key Cell