How to Find the Server Control ID of a RadGrid

Let’s say you have 2 RadGrids defined in your aspx page. Both grids happen to share the same ItemDataBound event, but you’d like to apply a small tweak depending on what grid is calling the ItemDataBound method.

In order to implement your tweak, you’ll need a way to find the ID of the grid that made the call. And not the ASP.NET generated ID, since that can be rather ugly, but the ID of the control you created in the aspx page. The following example demonstrates how this can be achieved:

1
2
3
<radG:RadGrid ID="rgThisYearsItems" runat="server" OnItemDataBound="rgItems_ItemDataBound"></radG:RadGrid>
 
<radG:RadGrid ID="rgLastYearsItems" runat="server" OnItemDataBound="rgItems_ItemDataBound"></radG:RadGrid>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
protected void rgItems_ItemDataBound(object sender, GridItemEventArgs e)
{
        // we need to determine what grid is calling the itemdatabound event
        RadGrid grid = (RadGrid)e.Item.OwnerTableView.OwnerGrid;
 
        if (grid.ID == "rgThisYearsItems")
        {
            // perform some logic here
        }
 
        if (grid.ID == "rgLastYearsItems")
        {
            // perform some logic here
        }
}

The reason you might want to implement the above is for code reuse. If you’ve got two grids and the ItemDataBound event for both will be really similar minus a line or two, you can have them both call the same ItemDataBound event and use the above logic to determine when to run the custom pieces.

Thoughts?

No comments yet.

Leave a Reply