简体   繁体   中英

How can I get a reference to a label so I can change one of it's properties?

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?

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;
    }
}

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;   
  }
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM