So here’s the idea. I’ve got a RadGrid on my page that is populated programmatically. I build a DataTable from various different sources and once I’m satisifed with how my DataTable looks, I set the grid’s DataSource property and bind.

That’s all good, except now I want to insert a header row in the middle of my grid. The idea behind this row is to simply provide a clear segregation between my different sources of data. It’s all one grid remember, but I wanted a way to distinguish between the data.

I came up with the idea to simply add a header row at the point I needed, set the ColumnSpan to match the number of columns I have in my grid, set the HorizontalSpan to center the text and finally set the Visibility on all other columns to false.

Here is what I ended up with. The grid is setup with 5 columns: Name, Address, City, Province and Country. At the point where I’d like my see my header row in the grid, I set the Name column to the text I’d like the header to contain. Keep in mind that I have rows being added before and after the code sample below. I’ve inserted the code exactly where I want my header to appear:

1
2
3
DataRow row = dt.NewRow();
row["Name"] = "My heading that I'd like to show";
dt.Rows.Add(row);

Now in the ItemDataBound event, I can modify this particular row that I just created so that it spans all the columns and is centered as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem) 
    {
        GridDataItem dataItem = e.Item as GridDataItem;
 
        // i use the second index to get at the name column. the first two indexes
        // are empty for me and don't contain any valuable data
        if (dataItem.Cells[2].Text == "My heading that I'd like to show")
        {
            dataItem["Name"].ColumnSpan = 8;
            dataItem["Name"].HorizontalAlign = HorizontalAlign.Center;
 
            dataItem["Name"].BackColor = System.Drawing.Color.Black;
            dataItem["Name"].ForeColor = System.Drawing.Color.White;
 
            dataItem["Address"].Visible = false;
            dataItem["City"].Visible = false;
            dataItem["Province"].Visible = false;
            dataItem["Country"].Visible = false;
       }
    }
}

That’s what I came up with and it seems to work great. If anyone has a better technique for implementing this, please let me know.

Tagged with:  

Leave a Reply

You must be logged in to post a comment.