我有这个简化的代码:
<asp:ListView ID="ListView1" runat="server" DataSourceID="sqldatasource1">
<ItemTemplate>
<asp:Button ID="ButtonTest" runat="server" BackColor="Silver" Text="Add to Cart" />
</ItemTemplate>
</asp:ListView>
我正在尝试在按钮后面运行一些代码,但我不知道如何运行。我无法在 ListView 中访问它。这并不重要,但我试图从当前 ListView (产品 ID)获取信息并将其传递到下一页。
有人知道如何用确切的代码来解决这个问题吗?谢谢!
最佳答案
您需要 ItemCommand
事件。您可以为按钮指定一个命令名称、一个命令参数(如果需要),然后监听 ListView 上的 ItemCommand 事件
<asp:ListView ID="ListView1" runat="server" OnItemCommand="DoTheCommand" DataSourceID="sqldatasource1">
<ItemTemplate>
<asp:Button CommandName="Foo" CommandArgument='<%#Eval("SomeDataBoundProperty")%>' ID="ButtonTest" runat="server" BackColor="Silver" Text="Add to Cart" />
</ItemTemplate>
</asp:ListView>
在你的代码后面:
void DoTheCommand(object sender, ListViewCommandEventArgs e) {
string commandName = e.CommandName;
object commandArg = e.CommandArgument;
ListViewItem selectedItem = e.Item;
int dataItemIndex = selectedItem.DataItemIndex;
if (commandName == "Foo") {
//and so on
}
}
关于asp.net - 如何访问 ListView 中的按钮?特别是使用button_click来执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351074/