简体   繁体   中英

CheckBox CheckedChanged event added from code behind

I have a couple of checkboxes that I add from my code behind, but I can't get the CheckedChanged event to fire.

This code is being called on page load:

CheckBox cb = new CheckBox();
cb.AutoPostBack = true;
cb.CheckedChanged += cb_CheckedChanged;

cb.ToolTip = dr["Id"].ToString();
cb.ID = Guid.NewGuid().ToString();

Label lbl = new Label();
lbl.Text = dr["Id"].ToString();
lbl.AssociatedControlID = cb.ID;

dvCheckboxes.Controls.Add(cb);
dvCheckboxes.Controls.Add(lbl);
dvCheckboxes.Controls.Add(new LiteralControl("<br />"));

And the event:

void cb_CheckedChanged(object sender, EventArgs e)
{
    System.Diagnostics.Debug.Write(((CheckBox)sender).ToolTip);
}

I've put a breakpoint in the CheckedChanged event, but it's never reached.

What I've tried:

  • putting the code in if(!IsPostBack) , but no difference.
  • cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
  • cb.CheckedChanged += new EventHandler(this.cb_CheckedChanged);
  • cb.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
  • tried putting the code in Page_Init instead of Page_Load

@johan, Try this. Create the checkboxes in PageInit instead of Pageload. Also provide an appropriate id for the Checkbox.

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Page_init(object sender, EventArgs e)
        {
            CheckBox cb = new CheckBox();
            cb.AutoPostBack = true;
            cb.CheckedChanged +=cb_CheckedChanged;
            cb.CausesValidation = false;
            cb.ToolTip = "Hello";
            cb.ID = "chk_test";

            Label lbl = new Label();
            lbl.Text = "test";
            lbl.AssociatedControlID = cb.ID;

            dvCheckboxes.Controls.Add(cb);
            dvCheckboxes.Controls.Add(lbl);
            dvCheckboxes.Controls.Add(new LiteralControl("<br />"));
        }
        protected void cb_CheckedChanged(object sender, EventArgs e)
        {

            System.Diagnostics.Debug.Write(((CheckBox)sender).ToolTip);
        }

Add event in your site code - not code behind:

<asp:CheckBox ID="cb" Runat="server" CheckedChanged="cb_CheckedChanged" />

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM