0

On a windows form, there are a group of checkboxes, chx1, chx2, chx3....chx20.

I need to loop through 1-20 and set the Checked property of these checkboxes. Is there a function that would accept the checkbox name as a string, the property to get or set as a string, and the value to set the property)?

Set:

GetSetProperty("chx1", "Checked", true);

or

Get:

GetSetProperty("chx1", "Checked");
2
  • Please elaborate on this. Why not just use this: foreach(var cb in this.Controls.OfType<CheckBox>()) cb.Checked = true;? Commented Aug 9, 2011 at 14:47
  • I am creating a set of checklist that users must complete. Based on database values, I need to set the items that have been marked complete. For instance, each numeric value(1-20) is either complete or not complete(1 - true, 2 - false, 3 - true, etc.) It is not a good option for this application to bind these checkboxes to a dataset. Commented Aug 9, 2011 at 14:59

3 Answers 3

3
((CheckBox)this.Controls["checkBox1"]).Checked = true;

Try something along the lines of this.

Sign up to request clarification or add additional context in comments.

1 Comment

Wanted to give this answer, i'm too slow :D
0

You can use Reflection to do exactly what you're talking about, but it's easier (IMO) and faster to just put the checkboxes in an array and use the index to find/manipulate them. If you do this though, be careful, because your checkboxes are indexed from one while arrays are indexed from zero, so you'll have to account for the one-off difference.

Comments

0

You can use LINQ to perform this and it will build the list of items checked or not checked (you can also do a foreach and check or uncheck them all.

var checkedBoxList = container.Controls.OfType<CheckBox>().FirstOrDefault(
r => r.Checked);

foreach(CheckBox chkbox in CheckedBoxList)
{ chkbox.Checked = false;} 

The container should be what hosts all the controls. You could set this as your form and it will get all of them or you can select the specific groupbox/panel.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.