Showing posts with label WinForms. Show all posts
Showing posts with label WinForms. Show all posts

Friday, June 26, 2009

TabControl and the Appearance property

How insane. I had set the Appearance property of the Tabcontrol to "Buttons" and thought, "That looks cool!" I also set the Alignment to "Bottom". Something different and pretty slick-looking.

But then I spent the next few hours trying to figure out why my custom control that I dropped on one of these tab pages wouldn't render. I kept thinking there was something wrong with the custom control. Finally, after a Google, http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.appearance(VS.71).aspx explained it all.

Selecting "Buttons" or "FlatButtons" for the TabControl's Appearance property requires that the Alignment be "Top". Of course, the notation just says that the alignment must be "Top" or the "Buttons" won't display correctly. It doesn't say anything about any other controls, which is what I experienced.

Alignment to "Top" if altering the Appearance on the TabControl to Buttons or FlatButtons.

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.