Tuesday, June 10, 2008

Add Grouped / Multiple row Header in the GridView

GridView the awesome control of the dot net is made so extendable that you can achive most thing you can thought about ,recently i

got the requirement that i have to show multiple row header in my application so i do some rearch and go a very simple solution.

Here we go.

What You have to do is just write some line of the code in the gridview RowDataBound event like

protected void GridViewData_RowDataBound(object sender, GridViewRowEventArgs e)

SortedList FormatCells = new SortedList();
FormatCells.Add("1", ",1,2");
FormatCells.Add("2", "TopGroup,4,1");

SortedList FormatCells2 = new SortedList();
FormatCells2 .Add("1", "Subgroup1,2,1");
FormatCells2 .Add("2", ""Subgroup2,1,1");
GetMultiRowHeader(e, FormatCells2 );
GetMultiRowHeader(e, FormatCells );

And Here is the function

public void GetMultiRowHeader(GridViewRowEventArgs e, SortedList GetCels)

if (e.Row.RowType == DataControlRowType.Header)
GridViewRow row;
IDictionaryEnumerator enumCels = GetCels.GetEnumerator();

row = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
while (enumCels.MoveNext())

string[] count = enumCels.Value.ToString().Split(Convert.ToChar(","));
TableCell Cell;
Cell = new TableCell();
Cell.RowSpan = Convert.ToInt16(count [2].ToString());
Cell.ColumnSpan = Convert.ToInt16(count [1].ToString());
Cell.Controls.Add(new LiteralControl(count [0].ToString()));
Cell.HorizontalAlign = HorizontalAlign.Center;
Cell.ForeColor = System.Drawing.Color.White;

e.Row.Parent.Controls.AddAt(0, row);