简体   繁体   中英

Asp.Net .findcontrol() when control doesn't exist

I have ran into this two days in a row now. If the label exists, this code works:

Label lblQuantity1 = ((Label)GridView1.FooterRow.FindControl("txtQty1f"));

If it doesn't, it throws an Object reference not set to an instance of an object.

Is there any way to catch this outside of Try/Catch blocks? I would think something like this, but it does not:

if ((Label)GridView1.FooterRow.FindControl("txtQty1f") != null)
{
// do something.
}

I've tried casting to objects and seeing if they are null. Doesn't work.

The only thing I have found that works if the label isn't there is to wrap it in Try/Catch blocks. Just seems like there should be a better way than that.

Thanks,

Usepattern matching for null safe casting.

if(GridView1.FooterRow.FindControl("txtQty1f") is Label lblQuantity1){
   //safely access lblQuantity1
}

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