Dynamically (programatically) adding check boxes and checkedchanged events

前端 未结 8 523
情歌与酒
情歌与酒 2020-12-19 18:21

I am having a bit of a problem adding a few check boxes and an event handler programatically. The check boxes all appear fine, but they don\'t do anything when clicked. Does

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 18:44

    I copied your code into a new VS2005 C# web project (see below). Your code works. There may be something else going on outside of this snippet. Or, is the StatementText property in all of your statements collection always empty?

    Page...

    
        
    Instructions: WorkPlaceHazardsBox:

    Code behind...

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    namespace CheckboxMadness
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                List statements = new List(new string[] { "foo", "bar" });
    
                foreach (string i in statements)
                {
                    CheckBox box = new CheckBox();
                    box.Text = i;
                    box.AutoPostBack = true;
                    box.CheckedChanged += new EventHandler(this.CheckedChange);
                    PlaceHolder1.Controls.Add(box);
                }
    
            }
            protected void CheckedChange(object sender, EventArgs e)
            {
                CheckBox x = (CheckBox)sender;
    
                Instructions.Text = "change";
    
                WorkPlaceHazardsBox.Text += x.Text;
            }
        }
    }
    

提交回复
热议问题