Monday, August 9, 2010

Retrieving selected row's key from Telerik RadGrid

This approach easily gets old:

TextBox1.Text = grdCategory.SelectedItems[0].OwnerTableView.DataKeyValues[grdCategory.SelectedItems[0].ItemIndex]["category_id"].ToString();

To make retrieving of key simpler for single select and single key on RadGrid, make an extension method for it:

public static class Helper
{
    public static object SingleSelectKeyValue(this Telerik.Web.UI.RadGrid rg)
    {
        return rg.SelectedItems[0].OwnerTableView.DataKeyValues[rg.SelectedItems[0].ItemIndex][rg.MasterTableView.DataKeyNames[0]];
    }
}

To use:

protected void grdCategory_SelectedIndexChanged(object sender, EventArgs e)
{
    TextBox1.Text = grdCategory.SingleSelectKeyValue().ToString();
}

No comments:

Post a Comment