Reputation: 43
I wrote this method to disable the autosize property of all labels whose name doesn't contain the string "Label".
private void DisableAutoSize()
{
foreach (Control control in Controls)
{
if (!control.Name.Contains("Label"))
{
(control as Label).AutoSize = false;
}
}
}
The line below is what causes the problem:
(control as Label).AutoSize = false;
The error I get says:
System.NullReferenceException: 'Object reference not set to an instance of an object.' (... as System.Windows.Forms.Label) returned null.
How can I access that AutoSize property?
Upvotes: 0
Views: 952
Reputation: 35680
filter Controls by type and apply search condition using LINQ methods OfType() and Where():
private void DisableAutoSize()
{
foreach (Label control in Controls.OfType<Label>().Where(c => !c.Name.Contains("Label")))
{
control.AutoSize = false;
}
}
Upvotes: 1
Reputation: 18155
The issue with your code is that Controls
could contain non-Label controls as well. If you were cast a non-Label Control as Control (control as Label
), it would return null. This is the reason you end up with NullReferenceException
.
You can Filter Label Controls using Enumerable.OfType<T>
method. For example,
foreach (Label control in Controls.OfType<Label>())
{
if (!control.Name.Contains("Label"))
{
control.AutoSize = false;
}
}
You can further expand the Linq to filter Labels based on the Name property using Enumerable.Where<T>
, thus removing the if condition.
foreach (Label control in Controls.OfType<Label>().Where(x=>!x.Name.Contains("Label")))
{
control.AutoSize = false;
}
Upvotes: 0
Reputation: 1610
You are looping through all of the Control
s in the form, at least one of which isn't a Label
. Thus, the cast fails. In your loop, check for this condition:
private void DisableAutoSize()
{
foreach (Control control in Controls)
{
Label label = control as Label;
if (label == null || control.Name.Contains("Label"))
{
continue;
}
label.AutoSize = false;
}
}
Upvotes: 0