I want to loop through and wire all the checkboxes "checkedchanged" events to a custom method.
Can I loop through InitializeComponent() and wire it up? If so, can someone post some code?
Here is what i was thinking and hope to do. Please offer any advice or better way to do this.
foreach (object obj in this.Controls)
{
if (typeof(obj) == System.Windows.Forms.CheckBox)
{
obj.click += new System.EventHandler(
}
}
Thanks
DanielPosted Nov 14, 2007, 10:01 AM
Thanks a million for the suggestion. I appreciate it.
Here's what I did.
I created a method and put the code there and made the call from the constructor after initizializecomponents is called. It seems to be working fine.
Here's the code:
private void CustomInitializeComponents()
{
//iterate tabpages collection
foreach (Control ctrl in this.tabClassProdEng.TabPages)
{
//if tab page, go through the controls on the tab page
if (ctrl is TabPage)
{
//TabPage tb = (TabPage)cc;
foreach (Control cb in ctrl.Controls)
{
//if checkbox, then wire the event
if (cb is CheckBox)
{
((CheckBox)cb).CheckedChanged += new System.EventHandler(this.SaveQuestion);
}//end if
}//end foreach
}//end if
}//end for each
}
AlanPosted Nov 13, 2007, 6:35 PM
Yes, you can do something like that but I wouldn't put the code in the InitializeComponent() method because, if you do, you risk getting it overwritten by the designer the next time you make a change to the form's visual interface. Instead, I'd put it either in the form's constructor (after the call to InitializeComponent()) or in Form_Load.
I'd suggest the following code which is not very different from what you had:
foreach (Control ctrl in this.Controls));
{
if (ctrl is CheckBox)
{
((CheckBox)ctrl).Click += new System.EventHandler(
}
}
This code assumes that all the CheckBoxes have been placed directly on the form. If they're inside some other container such as a panel, then replace 'this.Controls' with 'panel1.Controls' or whatever.