Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checkboxes, tons of 1

Status
Not open for further replies.

Doa667

Programmer
Jun 2, 2008
4
IL
Hi,
I need help with Checkboxes.
I set up a C# Form with 40 Checkboxes.
Now I need to step through them one by one to see if one is checked or not.
Later I want to write down something like:
1-20, 22, 24, 28-35, 37 are checked.

Can you help me?

I named the Checkboxes : cb_01 - cb_40
Currently I am trying to do something like

Code:
for (int i = 1;	i < 40; i++) 
{
    string sNr = "cb_" + i.ToString();
    if (Controls[i].Name == sNr)
    {
	    ...				
	}
	l_dbTest.Text	= ...
}
But does not work, because the controls seem to be mixed up.
What can I do?
 
add the checkboxes to a List<CheckBox>();
when needed iterate over the list and check if it's selected. if so add that to a List<int>().
then iterate over the int list to create your pretty format.
Code:
IList<CheckBox> checkboxes = new List<CheckBox>();
checkboxes.Add(cb_01);
checkboxes.Add(cb_02);
...
IList<int> selected = new List<int>();
foreach(CheckBox cb in checkboxes)
{
  if(cb.Checked) selected.Add(int.Parse(cb.Value);
}
selected.Sort();
...
//logic to create custom text

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Here comes the main problem.
I do not want to write
..Add(cb_01), but rather call them via

Code:
stringA = "cb_"+i.ToString();
checkboxes.Add(stringA);

But I cannot make it to work.
 
you cannot implictly convert a string to a control you need to either locate the control, or create a new control and set the id.

if you must define checkboxes by id then either
1. create the checkboxes dynamically and add them to the form and the list<>.
or
2. start at the main form and recursively loop through all controls until you find all the checkboxes.

btw:
Code:
int i = 1;
"cb_"+i.ToString();
//cb_1
Code:
int i = 1;
"cb_"+i.ToString("00");
//cb_01

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Thanks for the ToString comment. really helpful.
 
Specialty Bakers, Inc. ???
Do you have a link to that company. All I get is a bread shop :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top