Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RadGrid Get Selected Row Index from Item Template Button

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?

like image 624
bumble_bee_tuna Avatar asked Oct 23 '11 23:10

bumble_bee_tuna


2 Answers

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];
}
like image 109
James Johnson Avatar answered Nov 05 '22 07:11

James Johnson


You can use CommandName="" instead of OnClick.

Also add onitemdatabound="RadGrid1_ItemDataBound" to the main telerik:RadGrid tag.

Then in the code behind:

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem dataItem = e.Item as GridDataItem;

                int selectedRowIndex = dataItem.RowIndex;
    }
}
like image 37
Aineislis Cole Avatar answered Nov 05 '22 07:11

Aineislis Cole