General Control(s) question

D

Doug

HI,

I have a user control where checkboxes are added to it dynamically from the
database. I want to be able "tell" the parent form what has been checked
and what hasn't. I know I have to iterate through the controls on the form,
check to see if the control's name has part of a substring to determine if
it is one of the controls i'm looking for and then cast it to the checkbox
type and return what i need. The ONLY issue i have is I'm not sure how to
do all that. I know what i need to do, just not sure how to do it.

i have the following as my starting point, but not sure where to go from
here. Can someone please help me w/ a quick example. Thanks in
advance.....

foreach(Control ctrl in this.Controls)
{
.....

}


Doug
 
J

John Wood

foreach(Control ctrl in this.Controls)
{
if (ctrl.Name.IndexOf("your-substring")>=0)
{
CheckBox chk = (CheckBox)ctrl;
if (chk.Checked)
... // perform your action here, you have chk.Name and chk.
}
}
 
R

Rhy Mednick

If the only reason you're checking the name is to be sure that the item is a
checkbox then you don't need to bother. You could use the "is" operator to
find out.

foreach (Control ctl in this.Controls)
{
if (ctl is CheckBox)
{
CheckBox chk = (CheckBox)ctl;
}
}

Another option would be to hook the event for the checkbox and then just let
it tell you its state instead of you having to go look for it:

private void SomeMethod ()
{
CheckBox chk = new CheckBox();
this.Controls.Add (chk);
chk.CheckedChanged += new EventHandler (chk_CheckedChanged);
}
private void chk_CheckedChanged(object sender, EventArgs e)

{

CheckBox chk = (CheckBox)sender;

if (chk.Checked)

//do something...

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top