c# - How to add ListItem to DropDownList from code and get the selected value -


i succeeded adding list-items dropdownlist database, after ran application , selected value dropdownlist, checked break point @ code , saw selected value wrong. selects first value.

my code is:

userbll ubll = new userbll(); list<item> list = ubll.getallitemscategory(); foreach (item item in list) {     int var = 1;     listitem litem = new listitem(item.name, var.tostring());     modelslist.add(litem);     var++; }  dropdownlist2.datasource = modelslist;   dropdownlist2.databind(); 

how can fix when following executed i'll right selection , not first item?

order.nameitem = dropdownlist2.selectedvalue; 

you need check !ispostback in page_load event, this:

protected void page_load(object sender, eventargs e) {     if(!ispostback)     {         // put logic here bind         dropdownlist2.datasource = modelslist;           dropdownlist2.databind();     } } 

Comments

Popular posts from this blog

ruby on rails - Is it the correct way to implement belongs_to relation with factory girl? -

geolocation - Windows Phone 8 - Keeping background location tracking active beyond four hours -

Uncaught TypeError: Cannot read property 'parentNode' of null javascript -