[英]How to access Listview items to codebehind using asp.net
Iam using a listview to display table contents,How can i access a values form listview to code behind in button click 我使用列表视图显示表内容,我如何访问列表视图中的值以在按钮单击中隐藏代码
aspx 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 aspx.cs
protected void Button1_Click(Object sender,
System.EventArgs e)
{
//I want to access value here
}
I want to get Movie Name,Movie Genre,Runtime to code behind.. Any help is appreciated.. 我想获取电影名称,电影体裁,运行时后面的代码。.谢谢您的帮助。
Proper way to deal with button control click event in data bound controls is by setting a CommandArgument
& CommandName
properties. 处理数据绑定控件中的按钮控件单击事件的正确方法是通过设置CommandArgument
和CommandName
属性。 Instead of registering a click handler of button you can register a ItemCommand
event of ListView. 可以注册ListView的ItemCommand
事件,而不是注册按钮的单击处理程序。 This way whenever a button is clicked then this event is raised and you can find the data correctly like this:- 这样,无论何时单击按钮,都会引发此事件,您可以像这样正确地找到数据:
Add CommandName
& CommandArgument
properties to your button and remove the click handler:- 将CommandName
和CommandArgument
属性添加到您的按钮并删除单击处理程序:-
<asp:Button ID="Button1" runat="server" Text="Approve" CommandName="GetData"
CommandArgument='<%# Eval("MovieId") %>' ></asp:Button>
Next, register the ItemCommand
event with your listview:- 接下来,使用您的列表视图注册ItemCommand
事件:
<asp:ListView ID="lstMovies" runat="server" OnItemCommand="ListView1_ItemCommand">
Finally in the code behind, in ListView1_ItemCommand
method check if event is raised by your button and find all the respective controls:- 最后,在后面的代码中,在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..
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.