I’ve built a Winforms table layout which has many elements in each cell. What I’m trying to do is enumerate all controls of a particular type which I’m concerned with, and remove their corresponding Click values. This something done at runtime, which is why I’m not just setting the controls initial properties.
I’ve tried working with the Control.ControlCollection property although I’ve not had much luck, as it’s not IEnumerable. Alternative I have the following code but the problem is the control is never found in Controls and a Null Reference exception is thrown because I’m, trying to set .Click on an empty object, but surely this object should exist! Help!?
for (int row = 1; row < tblLayoutPanel.RowCount; row++)
{
for (int column = 0; column < tblLayoutPanel.ColumnCount; column++)
{
Type controlType = tblLayoutPanel.GetControlFromPosition(column, row).GetType();
if (controlType == typeof(CTLLabel) ||
controlType == typeof(OutputLabel))
{
Controls[tblLayoutPanel.GetControlFromPosition(column, row).Name].Click += null;
// Control is never found! *why?*
}
}
}
The reason is that the parent control of the control that you are getting using
GetControlFromPositionmethod istblLayoutPanel. You are trying to get the child control of thetblLayoutPanelin the parent of thetblLayoutPanelcontrol instead oftblLayoutPanel.Controlscollection.Instead of accessing the control like this, why you don’t just use the control you’ve got by using
GetControlFromPositionmethod. Try this:tblLayoutPanel.GetControlFromPosition(column, row).Click