Get and Set Checkbox properties, using checkbox names as strings
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 wo开发者_Go百科uld 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");
((CheckBox)this.Controls["checkBox1"]).Checked = true;
Try something along the lines of this.
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.
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.
精彩评论