开发者

problem with drop down list

开发者 https://www.devze.com 2023-01-28 11:07 出处:网络
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 regardl

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. :(


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
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消