DataListItem to DropDownList or TextBox VB.Net

2.3k Views Asked by At

I have a DataListItem which can potentially be a dropdownlist or a textbox. To get the value I would need to do:

 CType(item.FindControl("myControl"), TextBox).Text

Or

CType(item.FindControl("myControl"), DropDownList).SelectedValue.ToString()

The problem is, if it's a dropdownlist I get..

Unable to cast object of type 'System.Web.UI.WebControls.DropDownList' to type 'System.Web.UI.WebControls.TextBox'.

Is there a way to check if the CType will take before Ctyping it?

1

There are 1 best solutions below

0
On BEST ANSWER

Use TryCast:

Dim txt as TextBox = TryCast(item.FindControl("myControl"), TextBox)
If txt Is Nothing Then
    TryCast(item.FindControl("myControl"), DropDownList)
End If