Question

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?

Was it helpful?

Solution

Use TryCast:

Dim txt as TextBox = TryCast(item.FindControl("myControl"), TextBox)
If txt Is Nothing Then
    TryCast(item.FindControl("myControl"), DropDownList)
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top