在Page_Load上创建并放置按钮,然后将它们绑定到单个事件

时间:2013-09-16 06:39:30

标签: c# asp.net

我正在使用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);

我想在“rating”div中插入2个按钮/链接,用于页面上的每个评论。这两个按钮用于喜欢和不喜欢评论,如何以编程方式创建,将它们绑定到事件,然后检查您点击按钮的注释?

1 个答案:

答案 0 :(得分:0)

此代码将两个嵌套的div插入到页面中,并将两个按钮添加到内部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;
        }
    }