1
votes

I have a drop down list control populated with items and some code to take the currently selected item value. The problem is I only get the value of the first item in the list regardless of what item is actually selected.

Here is my code to populate the drop down:

protected void displayCreateCategories()
{
    StoreDataContext db = new StoreDataContext();
    var a = from c in db.Categories
                    orderby c.Name
                    select new{catName= c.Name,
                        catId=c.CategoryID};

    ddlCategory.DataSource = a;
    ddlCategory.DataTextField = "catName";
    ddlCategory.DataValueField = "catId";
    ddlCategory.DataBind();   
}

To get the value of the currently selected item which in my case is always of type integer I do label1.text=Convert.toInt32(ddlCategory.SelectedValue);

I get the selected value, but it is always for the 1st item in the list. I'm pulling my hair out over this. :(

2

2 Answers

4
votes

I suspect you're running the list loading code every time the page loads, which is destroying the list, repopulating the list, and auto-selecting the first item before your selection retrieval code gets run.

Use this construction in Page_Load:

if (!IsPostBack)
{
    // Initial control population goes here
}
1
votes

Data binding will reset the control's selected value so make sure you retrieve the selected value before data binding on postback.