在Page_Load上创建并放置按钮,然后将它们绑定到单个事件
本文关键字:然后 绑定 事件 单个 按钮 Load Page 创建 | 更新日期: 2023-09-27 18:31:22
我正在使用 ASP.NET(C#)制作注释系统,注释存储在XML文件中,然后在Page_Load上格式化为div。
comments.InnerHtml += String.Format(
"<div class='"comment_body'">" +
"<img class='"gravatar'" src='"{0}'"/>" +
"<span class='"name'">{1}<strong class='"date'">{2}</strong></span><br/>" +
"<div class='"rating'"> !Thumbs up, thumbs down, # thumbs up votes # and #thumbs down votes goes here</div>"+
"<span class='"message'">" +
"{3}" +
"</span>" +
"</div>"
, gravatar, name, date, message);
我想在"评级"div 内为页面上的每条评论插入 2 个按钮/链接。这两个按钮用于喜欢和不喜欢评论,我如何以编程方式创建,将它们绑定到事件,然后检查您从哪个评论中单击了该按钮?
此代码将两个嵌套的div 插入页面,并将两个按钮添加到内部div,并将单击事件绑定到每个按钮。在事件处理方法中,每个按钮都可以通过其 id 来标识:
protected void Page_Load(object sender, EventArgs e)
{
// add comment div
Panel pnl = new Panel();
pnl.CssClass = "comment_body";
form1.Controls.Add(pnl);
// add rating div
Panel pnlRating = new Panel();
pnlRating.CssClass = "rating";
pnl.Controls.Add(pnlRating);
// button 1
Button btn = new Button();
btn.ID = "uniqueId"; // here you set a unique id, which you can check in button click
btn.Text = "Click me";
btn.Click += new EventHandler(btn_Click);
pnlRating.Controls.Add(btn);
//button 2
Button btn2 = new Button();
btn2.ID = "uniqueId2"; // here you set a unique id, which you can check in button click
btn2.Text = "Click me";
btn2.Click += new EventHandler(btn_Click);
pnlRating.Controls.Add(btn2);
}
void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// identify the button by id
switch (btn.ID)
{
case "uniqueId":
break;
case "uniqueId2":
break;
}
}