Wednesday, June 24, 2009

Finding a control within a control

I have a case where I need to get a particular control out of a container of controls. I don't know the name of the control, although I am prefixing it with a specific pattern, because I'm adding the control dynamically, and there could be any number of these controls.

I found Control.ControlCollection.Find, but the Help for it (http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.find.aspx) did not give any examples using a wildcard matching. Yes, I could iterate through all controls, but that seems inefficient. Yes, I could use LINQ, but this project has the limitation of being required to be .NET 2.0, not .NET 3.5.

So, time for the sandbox. Simple test: I create a form, with a groupbox (groupBox1) and put three controls in it. One Button control named "button1" and two CheckBox controls named "checkBox1" and "checkBox2". Then ran this code:

Control

[] ctl = groupBox1.Controls.Find("checkBox*", true

);

Control[] ctl1 = groupBox1.Controls.Find("checkBox1", true

);

Control[] ctl2 = groupBox1.Controls.Find("checkBox2", true);

ctl had no elements, while ctl1 and ctl2 both had one element (due to the exact match). I also tried changing "checkBox*" to just "checkBox" with the same result.

Well, this was rather annoying. After all, what's the point of returning an array, if the best you're going to do is return one item?

Then, on an whim I tried the following code:

this

.checkBox1.Name = "test"

;

this.checkBox2.Name = "test"

;

Control[] ctl = groupBox1.Controls.Find("test", false);

And good news! I got two items back!

So the trick in my case was when I go to generate my dynamic control, I always set the "Name" property the same. Then Controls.Find will find all matches, since you cannot wildcard it.


No comments:

Post a Comment