ASP.net GridView: get LinkItem's row

2019-09-18 03:06发布

问题:

I want to show "Delete" link in GridView to registred users, therefore I am using templateField:

    <asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView_Sort">
    <Columns>
        <asp:TemplateField HeaderText="Control">
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" runat="server" onClick="deleteEntry()"  Text="Delete"></asp:LinkButton>
        </ItemTemplate>
        </asp:TemplateField>  
    </Columns>
    </asp:GridView>

Now in my deleteEntry() function how can I know anything about the row in which "Delete" link was clicked? How to ge for e.g. rowindex?

回答1:

You could approach this slightly different. You see, when a control is placed inside a gridview, any event raised from that control raises also the RowCommand on the GridView.

To get what you want you could then add both CommandName and CommandArgument to your LinkButton and then catch it in the GridView's RowCommand.

<asp:LinkButton id="LinkButton1" runat="server" commandName="LinkButtonClicked" commandArgument='Eval("myObjectID")' />

where myObjectID is the name of the ID column of your object you bind the grid to.

Then

void GridView1_RowCommand( object sender, GridViewCommandEventArgs e )
{
    if ( e.CommandName == "LinkButtonClicked" )
    {
        string id = e.CommandArgument; // this is the ID of the clicked item
    }
}