0

I'm making a comment system using ASP.NET (C#), comments are stored in a XML file which is then, on Page_Load, formatted inside a 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);

I want to insert 2 buttons/links inside the "rating" div, for each comment on the page. The two buttons are for Liking and Disliking the comment, how to I go about programmatically creating, binding them to an event and then checking what comment you clicked the button from?

4

1 回答 1

0

这段代码在页面中插入了两个嵌套的 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;
        }
    }
于 2013-09-16T07:12:43.810 回答