Wednesday, 8 April 2009

.Net Control Collection Gotcha

Making puff pastry is something that sounds like it should be easy but when you’ve got the butter, flour and mixing bowl out it turns out to be excessively difficult. In the same vein – iterating through a collection of .Net controls and finding all the ones that are checkboxes sounds straight forward but is in fact a bit of a pen chewer.

My first attempt. This is a winner surely.
foreach (Control control in thisPanel.Controls)
{

if (control.GetType() is CheckBox)
{
//never going to work
}

}
Nope – the compiler complains straight away that ‘Control control’ will never be of type checkbox. OK sounds reasonable. After some discussion with colleagues a fellow programming minion suggested that it’s the foreach that’s the problem – so try the following.

for (int i = 0; i < thisPanel.Controls.Count; i++)
{
if (thisPanel.Controls[i].GetType() is CheckBox)
{
//won’t get here either
}
}
Looking good – but sadly again won’t work. The problem is that the control collection has already been downcast to a generic control. Therefore it doesn’t ‘know’ anything of its original type. What’s a boy to do? The best 4 programmers could come up with a combined amount of programming experience of over thirty years was –
foreach (Control control in thisPanel.Controls)
{
CheckBox checkBox = control as CheckBox;

if (checkBox != null)
{
//now we can do something
checkBox.Enabled = false;
}
}
This solves the problem so hurray. I have a nagging feeling that there is a better solution. It seems a simple request that should be achievable without guessing what types are in there. It’s probably something wildly clever with generics/delegates/lambda expressions or some such. Further pondering required I think.

No comments: