How to know which LinkButton in a ListView was clicked

[亡魂溺海] 提交于 2019-12-01 09:16:51

问题


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



来源:https://stackoverflow.com/questions/8327665/how-to-know-which-linkbutton-in-a-listview-was-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!