-->

How to know which LinkButton in a ListView was cli

2019-02-20 02:35发布

问题:

I currently have a LinkButton in the ItemTemplate of a ListView. Each button in the ListView should call the same click event handler. However, in the handler I need to know which button was clicked. Is this possible?

<asp:ListView runat="server" ID="lvKeyGroup">
    <LayoutTemplate>
        <table>
            <asp:Placeholder runat="server" ID="itemPlaceholder" />
        </table>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
            <td>[<asp:LinkButton runat="server" Text="Remove" OnClick="lbRemoveAuthGroup_Click" />]</td>
            <td><%# Eval("AuthorizationGroup") %></td>
        </tr>
    </ItemTemplate>
</asp:ListView>

回答1:

Add CommandName property to each LinkButton and handle ListView's ItemCommand event.

Also you need to set ListView's DataKeys property to your datasource object unique identifier name. The you can get selected row datakey:

void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    // in assumption that your data item's unique identifier type is Int32
    var dataKey = (int)ListView1.DataKeys[e.Item.DataItemIndex].Value; 

    switch(e.CommandName)
    {
        case "Remove":
            // your code here
            break;
    }
}

Follow this link for ListView control overview: http://msdn.microsoft.com/en-us/library/bb398790.aspx

Also, watch this video: http://www.pluralsight-training.net/microsoft/players/PSODPlayer?author=dan-wahlin&name=webforms-03&mode=live&clip=0&course=aspdotnet-webforms4-intro