简体   繁体   中英

this.Controls returns null

There are similar questions to this on here but nothing that answers this specific issue. I'm creating a button object to dynamically amend the Image on the button. But using the code below, I get a "Object reference is not set to an instance of an object" when I try and set the Image on the button.

Button button3;
button3 = (Button)this.Controls["btnDay" + ctrlsFwd.ToString("00")];
button3.Image = Resources.BookingAllDay;

Any help appreciated! Go easy - it's my first post :-)

** Update - A bit of a facepalm moment. The buttons are in a panel, so I needed to refer to pnlCalendar.Controls and not this.Controls.

One way of doing this would be:

button3 = (Button)this.Controls
    .Find("btnDay" + ctrlsFwd.ToString("00"))
    .FirstOrDefault();

another way of doing it would be:

button3 = this.Controls.OfType<Button>()
    .Where(b => b.Name == "btnDay" + ctrlsFwd.ToString("00"))
    .FirstOrDefault();

As pointed out by Stefan , check for null :

if (button3 == null) { return; }

because it can happen.

Since this, button3 = (Button)this.Controls["btnDay" + ctrlsFwd.ToString("00")]; , is a perfectly valid way of accessing a control, and doesn't work, either a control with that name doesn't exist or more likely the control is inside a container. Either way searching for it in this isn't going to find it no matter how many different ways you try and find it.

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