Aug 5, 2009

Retrieving Keys of Selected Items in Telerik RadGrid

Telerik's grid control is fairly flexible, but at times can be a royal pain to use. Things that should be dirt simple are often ridiculously convoluted and impossible to figure out without wasting time digging through their documentation or visiting their support forums.

Here is how Telerik suggests getting the primary key for the first selected item in a RadGrid:

RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["CustomerID"]

I guess something like:

RadGrid1.SelectedItems[0].Value

would have been too obvious. Anyway, here is a helper routine I wrote to hand back an ArrayList containing the selected keys:

#region GetTelerikGridSelections
public ArrayList GetTelerikGridSelections(Telerik.Web.UI.RadGrid grid)
{
ArrayList selectedItems = new ArrayList();
if (grid.MasterTableView.DataKeyNames.Length > 0)
{
string key = grid.MasterTableView.DataKeyNames[0];
for (int i = 0; i < grid.SelectedItems.Count; i++)
{
selectedItems.Add(grid.MasterTableView.DataKeyValues[grid.SelectedItems[i].ItemIndex][key]);
}
}
return selectedItems;
}
#endregion

I used an ArrayList rather than a strongly-typed collection to make it more flexible, but if you always use the same data type for your keys, you could change this to save yourself some effort. Note: this only looks at the MasterTableView. If you are using multiple table views in your grid you should also tweak this to receive a GridTableView instead of a RadGrid.

3 comments:

  1. It will be a bit more easier if you use GetDataKeyValue() method of GridDataItem:

    object value = RadGrid1.SelectedItems[0].GetDataKeyValue("CustomerID");

    ReplyDelete
  2. i have a LinkButton in a RadGrid and i have a ID Field that i hide. So i want to to get the value of the ID Field if the linkButton is Clicked, i want to do this on the Client side. Do you have any idea.

    Vuyiswamb@Gmail.com

    ReplyDelete