tags:

views:

539

answers:

2

Hi All,

I am having problems getting the values of a dropdownlist from the FIndControl function.

Here is the code I am trying to use:

currentCategoryID = Convert.ToInt32(((DropDownList)r.FindControl("DDLCategories")));

The value of the currentCategoryID in the database is an "int"

When I execute the above code I get this error message:

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

Using the same code I have had to retireve textbox values using this code and all is ok

currentAddress = ((TextBox)r.FindControl("txtAddress")).Text;

Could someone please point me in the right direction on how to write this code correctly

+1  A: 

Your first snippet is trying to convert the DropDownList control itself to an int. What you need to do is extract the selected value or selected item or whatever, depending on what UI framework you're using:

object selectedId = ((DropDownList)(r.FindControl("...")).SelectedValue;
int currentCategoryId = Convert.ToInt32(selectedId);
itowlson
+1  A: 

You're trying to convert the DropDownList itself to an Int32 rather than its value. You should drill down further into the control to retrieve the value before you convert it. For example,

currentCategoryID = Convert.ToInt32(((DropDownList)r.FindControl("DDLCategories")).SelectedItem.Value);
Volte
Thanks Volte, I knew it was something simple I was forgtting.
Jason