我在asp.net网络表单中有一个DataList控件,在此DataLIst中,我有2个绑定到数据库的标签和一个按钮。
标签之一代表编号,另一代表股票。
我想捕获特定产品的按钮单击事件,然后将该产品添加到用户购物车中。
这是我的数据列表:
<asp:DataList ID="dListProduct" runat="server" RepeatColumns="4" OnItemCommand="dListProduct_ItemCommand">
<ItemTemplate>
<div>
<table class="table-responsive" border="1">
<tr>
<td>
<asp:Label runat="server" Text="Available Stock: " ></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("Stock")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Id" ></asp:Label><asp:Label ID="lblPId" runat="server" Text='<%# Eval("Product_Id")%>' Visible="false"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button id="btnAddtoCart" runat="server" Text="Add to Cart"/>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>
这是我在DataList的OnItemCommand事件中使用的代码:
protected void dListProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
Label lbl = (Label)e.Item.FindControl("lblPId");
Response.Write(lbl.Text);
}
但是这些代码永远不会执行。
谁能帮我吗?
最佳答案
完全按照我的方式将代码复制并粘贴到下面。
后面的代码:
public partial class DataListExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
MyStock stock1 = new MyStock { Product_Id = 1, Stock = "Stock 1" };
MyStock stock2 = new MyStock { Product_Id = 2, Stock = "Stock 2" };
dListProduct.DataSource = new List<MyStock> { stock1, stock2 };
dListProduct.DataBind();
}
protected void dListProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
Label lbl = (Label)e.Item.FindControl("lblPId");
Response.Write(lbl.Text);
}
}
public class MyStock
{
public int Product_Id { get; set; }
public string Stock { get; set; }
}
.ASPX:
<asp:DataList ID="dListProduct" runat="server" RepeatColumns="4" OnItemCommand="dListProduct_ItemCommand">
<ItemTemplate>
<div>
<table class="table-responsive" border="1">
<tr>
<td>
<asp:Label runat="server" Text="Available Stock: "></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("Stock")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Id"></asp:Label><asp:Label ID="lblPId" runat="server" Text='<%# Eval("Product_Id")%>' Visible="false"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnAddtoCart" runat="server" Text="Add to Cart" />
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>
关于c# - 如何从asp.net DataList捕获按钮单击事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37818913/