[英]Literal Control with an asp button
我正在使用ASP .NET创建一个电子商务网站,并使用如下文字控件将产品动态地从数据库添加到购物页面:
foreach (DataRow dr in dt.Rows)
{
string productName = dr["PRO_Name"].ToString();
string productPrice = dr["PRO_Price"].ToString();
string myUrl = "Handler.ashx?ProdID=" + dr["PRO_ID"].ToString();
string sProduct = @"<div class='four-shop columns isotope-item'><div class='shop-item'><figure><img src='" + myUrl + "'/><figcaption class='item-description'><h5>" + productName + "</h5><span>R" + productPrice + "</span></figcaption></figure></div></div>";
productPanel.Controls.Add(new LiteralControl(sProduct));
}
我想知道如何在文字控件中添加带有click事件的按钮。 我已经创建了此按钮,但是不能将其添加到文字控件中,因为文字控件仅显示标记,而不显示服务器端控件。 如何将每个按钮从数据库添加到购物页面中动态添加此按钮。
Button button = new Button();
button.Text = "Add to cart";
button.Click += button_Click;
而不是使用文字控件。 您可以将其直接添加到页面控件中,如果仍然热衷于使用容器控件,则可以使用面板控件。
问候,
我可能建议为您的产品建立一个用户控件。 构建一个控件,该控件具有例如:图像控件,用于描述的标签控件,用于价格等的标签以及用于添加到购物车的按钮等。
这样,您可以为每个要显示的产品动态创建控件,在添加按钮中添加代码,并根据代码为每个产品设置产品属性,例如图像,说明等。
用户控件将在页面上以普通HTML呈现,但是它允许您为每种产品在代码中使用“控件” /对象。
与其使用动态方法,不如使用Repeater。 这将使您免于头痛:
<asp:Repeater id="repeat" runat="server">
<ItemTemplate>
<div class='four-shop columns isotope-item'><div class='shop-item'><figure><img src='<%#string.Format("Handler.ashx?ProdID={0}",Eval("PRO_ID")) %>'/><figcaption class='item-description'><h5><%#Eval("PRO_Name")%> </h5><span><%#Eval("PRO_Name")%> </span></figcaption></figure></div></div>
<asp:button id="btnAdd" runat="server" Text="Add to Cart" OnClick="btnAdd_Click" />
</ItemTemplate>
</asp:Repeater>
然后在后面的代码中,为按钮单击定义处理程序:
protected void btnAdd_Click(object sender, EventArgs e)
{
//handle add for the product here
}
这样使用
Button button = new Button();
button.Text = "Add to cart";
button.Click += button_Click;
productPanel.Controls.Add(button );
添加文字控件之后。 如果要在LiteralControl
(即sProduct)之间的某个位置将其分成两部分。
像这样,
string sProduct = @"<div class='four-shop columns isotope-item'><div class='shop-item'><figure><img src='" + myUrl + "'/><figcaption class='item-description'><h5>" + productName + "</h5><span>R" + productPrice + "</span></figcaption></figure>";
productPanel.Controls.Add(new LiteralControl(sProduct));
Button button = new Button();
button.Text = "Add to cart";
button.Click += button_Click;
productPanel.Controls.Add(button );
productPanel.Controls.Add(new LiteralControl("</div></div>"));
但是,不建议像这样使用LiteralControl。 您可以在这种情况下使用HtmlGenericControl。
试试这种方法。
Table tb = new Table();
for (int i = 1; i <= 10; i++)
{
TableRow tr = new TableRow();
TableCell td = new TableCell();
Button bt = new Button();
bt.ID = i.ToString();
bt.Text = "Button " + i.ToString();
bt.Click += new EventHandler(btn_Click);
td.Controls.Add(bt);
tr.Controls.Add(td);
tb.Controls.Add(tr);
}
dvTest.Controls.Add(tb);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.