Retrieving Keys of Selected Items in Telerik RadGrid

by Al Beecy December 24, 2008
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.

Tags: ,

Asp.Net | Telerik

Comments

December 25, 2008 #

DotNetKicks.com

Trackback from DotNetKicks.com

Retrieving Keys of Selected Items in Telerik RadGrid

DotNetKicks.com

January 23, 2009 #

Web Development Community

Trackback from Web Development Community

Retrieving Keys of Selected Items in Telerik RadGrid

Web Development Community

February 28, 2009 #

LW

I share your sentiment exactly.  The Telerik products are nice - we bought them afterall.  However, things that should be relatively simple take aren't.

Thanks for your code, you set me on the right path to working through my problem.  Something Tech Support was unable to do.

LW United States

October 1, 2009 #

Anonymous

hey you can also use this syntax:
grid.SelectedValues["CustomerID"].

thanks,
Priyanka

Anonymous United States

November 6, 2009 #

Anonymous

thanks

Anonymous United States

Powered by BlogEngine.NET1.5.0.7 | Theme by Mads Kristensen