RadGrid Get Selected Row Index from Item Template Button

bumble_bee_tuna picture bumble_bee_tuna · Oct 24, 2011 · Viewed 42.8k times · Source

I am working on a project using Telerik controls. I'm trying to figure out how to get the selected row index on an ItemTemplate button click event, like in the markup below:

<telerik:RadGrid ID="RadGrid1" runat="server" AllowFilteringByColumn="True" 
    DataSourceID="cusGrid" GridLines="None" Skin="Default" AllowPaging="True" DataKeyValue="CustomerID" 
    PageSize="500" AllowMultiRowSelection="True" ShowStatusBar="true" >
        <MasterTableView AutoGenerateColumns="False" DataKeyNames="CustomerID" DataSourceID="cusGrid">
            <RowIndicatorColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </RowIndicatorColumn>
            <ExpandCollapseColumn>
                <HeaderStyle Width="20px"></HeaderStyle>
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridTemplateColumn UniqueName="CheckBoxTemplateColumn">
                    <ItemTemplate>
                        <asp:Button runat="server" Text="Select" OnClick="SelRecord" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
    ...

Normally with a GridView I would just do something like:

protected void SelRecord(object sender, EventArgs e)
{
    var gRow = (GridViewRow)(sender as Control).Parent.Parent;
    var key = string.Empty;
    if (gRow != null) { key = gRow.Cells[0].Text; }
}

What is the equivalent with the Telerik control?

Answer

James Johnson picture James Johnson · Oct 28, 2011

Use the CommandArgument, and use OnCommand instead of OnClick to get the row index:

<asp:Button ID="Button1" runat="server" CommandArgument='<%#Container.ItemIndex%>' OnCommand="Button1_Command" ... />

Code-behind:

protected void Button1_Command(object sender, CommandEventArgs e)
{
    GridDataItem item = RadGrid1.Items[(int)e.CommandArgument];
}