By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,854 Members | 876 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,854 IT Pros & Developers. It's quick & easy.

Dynamic Checkbox Problem in ASP .NET

P: 1
Hi All,

I created a dynamic checkbox in ASP .Net inside a Button1_Click event method (outside the page_load event) and performed the event handling method for the CheckedChanged event and when I check the checkbox at runtime nothing happens (checkBoxObj.check is always false). Does anyone have information on how to make this work? Note: I can get it to work inside Page_Load event. I need help in getting it to work in a different event method. See my below code snippet:


Expand|Select|Wrap|Line Numbers
  1. protected void Button1_Click(object sender, EventArgs e) 
  2.  
  3. // Create new CheckBox control. 
  4. CheckBox NewCheckBox = new CheckBox(); 
  5. NewCheckBox.ID = "CheckBoxId"; 
  6. NewCheckBox.Text = "Dynamic CheckBox"; 
  7. NewCheckBox.AutoPostBack = true; 
  8.  
  9.  
  10. //// Register the event-handling method for the CheckedChanged event. 
  11. NewCheckBox.CheckedChanged += new EventHandler(this.Check_Change); 
  12.  
  13. // Add the control to the Controls collection of the 
  14. // PlaceHolder control. 
  15. Place.Controls.Clear(); 
  16. Place.Controls.Add(NewCheckBox); 
  17.  
  18.  
  19.  
  20.  
  21. void Check_Change(Object sender, EventArgs e) 
  22.  
  23. // Retrieve the CheckBox control from the PlaceHolder control. 
  24. CheckBox check = (CheckBox)Place.FindControl("CheckBoxId"); 
  25.  
  26. // Display the appropriate message based on the state of the 
  27. // CheckBox control. 
  28. if (check.Checked) 
  29. TextBox1.Text = "I'm checked"; 
  30. else 
  31. TextBox1.Text = "I'm not checked"; 
  32.  


Thanks!
Sep 1 '08 #1
Share this Question
Share on Google+
1 Reply


Frinavale
Expert Mod 5K+
P: 9,731
You need to initialize your CheckBox control in the Page_Init code otherwise the control will not be loaded during postback and your event for the control will be lost.

Check out the article on how to use dynamic controls in ASP.NET

-Frinny
Sep 5 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.