如何使用asp.net访问Listview项目以代码隐藏

时间:2015-11-18 11:23:19

标签: c# asp.net

我使用listview来显示表格内容,如何在按钮点击中访问值表格列表视图后面的代码

ASPX

<LayoutTemplate>
<table runat="server" id="table1">
 <tr id="Tr1" runat="server">
    <th class="tablehead"id="mname">Movie Name</th>
    <th class="tablehead">Movie Genre</th>
    <th class="tablehead">Runtime</th>

 </tr>
<tr runat="server" id="itemPlaceholder"></tr>

  

<ItemTemplate>
<tr id="Tr2" runat="server" class="tablerw">
 <td style="background-color:#EEEEEE;width:100px;" class="tablerw"><asp:Label ID="Label5" runat="server" Text='<%#Eval("MovieName") %>' /></td>
 <td style="background-color:#EEEEEE;width:100px;"><asp:Label ID="NameLabel" runat="server" Text='<%#Eval("movieGenre") %>' /></td>
 <td style="background-color:#EEEEEE;width:100px;"><asp:Label ID="Label1" runat="server" Text='<%#Eval("Runtime") %>' /></td>
<td>
 <asp:Button ID="Button1" runat="server" Text="Approve" OnClick="Button1_Click"></asp:Button>//Here is my button
 </ItemTemplate>  

aspx.cs

 protected void Button1_Click(Object sender,
                    System.EventArgs e)
      {
       //I want to access value here
      }

我想让电影名称,电影类型,运行时代码落后......任何帮助都表示赞赏..

1 个答案:

答案 0 :(得分:1)

在数据绑定控件中处理按钮控件点击事件的正确方法是设置CommandArgument&amp; CommandName属性。您可以注册ListView的ItemCommand事件,而不是注册按钮的单击处理程序。这样,无论何时单击按钮,都会引发此事件,您可以正确地找到数据: -

添加CommandName&amp;按钮的CommandArgument属性并删除点击处理程序: -

<asp:Button ID="Button1" runat="server" Text="Approve" CommandName="GetData"
            CommandArgument='<%# Eval("MovieId") %>' ></asp:Button>

接下来,使用您的列表视图注册ItemCommand事件: -

 <asp:ListView ID="lstMovies" runat="server" OnItemCommand="ListView1_ItemCommand">

最后在后面的代码中,在ListView1_ItemCommand方法中检查按钮是否引发了事件并找到所有相应的控件: -

 protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
 {
     if (e.CommandName == "GetData")
     {
        if (e.CommandSource is Button)
         {
             ListViewDataItem item = (e.CommandSource as Button).NamingContainer 
                                      as ListViewDataItem;
             Label NameLabel = item.FindControl("NameLabel") as Label;
             Label Label5 = item.FindControl("Label5") as Label;
             //and so on..
         }
    }
}