如何在代码behinde中单击ListView ItemTemplate时访问按钮并执行一些操作?

时间:2015-04-01 09:06:39

标签: c# asp.net listview button click

的.aspx

  <asp:ListView ID="ListViewUsers" ItemType="User" runat="server" OnItemCommand="ListViewUsers_ItemCommand">
                        <ItemTemplate>
                            <div class="center">
                                <table id="tableUsers">
                                    <tr>
                                        <td><%#Item.UserName%></td>
                                        <td><asp:Button ID="Btn_addFriend"
                                             runat="server"  Text="Add friend" /></td>
                                    </tr>
                                </table>
                            </div>
                        </ItemTemplate>
                                   ...

.aspx.cs

protected void ListViewUsers_ItemCommand(object sender, ListViewCommandEventArgs e)
{
      // How to access the button, and do some work when it is clicked.
}

1 个答案:

答案 0 :(得分:0)

执行此操作的正确方法是将CommandName参数添加到Your按钮,然后在Your EventHandler中捕获它。示例如下:

<asp:Button ID="Btn_addFriend" runat="server"  Text="Add friend" CommandName="Add friend" />

现在您可以在事件处理程序中捕获此命令,如下所示:

protected void ListViewUsers_ItemCommand(object sender,ListViewCommandEventArgs e)
{
  if(String.Equals(e.CommandName, "Add friend"))
  {
    // ... DO SOME WORK HERE
  }
}

参考MSDN文章https://msdn.microsoft.com/pl-pl/library/system.web.ui.webcontrols.listview.itemcommand%28v=vs.110%29.aspx