B. Clay Shannon B. Clay Shannon - 4 days ago 4
Vb.net Question

Is it imperative that I change Label to Control to avoid a possible runtime error?

In trying to purify an inherited legacy VB.NET / ASP project, I'm resharperizing it, and it tells me, "Runtime errors might occur when converting 'System.Web.UI.Control' to 'System.Web.UI.WebControls.Label'" on this line:

Dim _UserNameLabel As Label = PortalLogin.FindControl("UserNameLabel")


...but when I acquiesce and let it change it to this:

Dim _UserNameLabel As Control = PortalLogin.FindControl("UserNameLabel")


...the "Style" property here reds up:

_UserNameLabel.Style("color") = dt1.Rows(0)("TextBoxColor")


Is there an alternate way to supply that Label/Control a color, am I better off ignoring Resharper's suggestion, or what?

Answer

The correct option is:

Dim _UserNameLabel = DirectCast(PortalLogin.FindControl("UserNameLabel"), Label)

The Control reference returned by FindControl is cast as type Label and you can then access members specific to type Label. It is Option Infer On that allows the type of the UserNameLabel variable to be inferred from its initialising expression. With Option Infer Off you would need to write:

Dim _UserNameLabel As Label = DirectCast(PortalLogin.FindControl("UserNameLabel"), Label)

Some people prefer to do that anyway, for clarity. Type inference is often handy but not required. Where it is required is in using anonymous types returned by LINQ queries.

Comments