c# - Drop Down List unexpected behaviour -


i have unexpected behaviour asp.net web forms dropdownlist. adding listitems drop down list, , looks well. except value in ddl (which in case id) never set, replaced text listitem.

<asp:dropdownlist id="ddl1" runat="server"> </asp:dropdownlist> private void populate() { list<listitem> list = new list<listitem>(); foreach (var item in getitems()) { list.add(new listitem(item.name, item.id.tostring())); //in drop down list listitem.value being replaced //by listitem.text when added ddl } ddl1.datasource = list; ddl1.databind(); ddl1.items.add(new listitem("make selection")); } private list<stuff> getitems() { list<stuff> list = new list<stuff>(); list.add(new stuff{ name = "bill", id = 1}); list.add(new stuff{ name = "james", id = 2}); return list; } private struct stuff { public string name; public int id; } 

any ideas if meant happen? , if how store both name , id in ddl?

in populate method, data binding, not specifying property should bind value in list of list items.

to need set datatextfield , datavaluefield properties.

you might find simpler change populate code following:

private void populate() { foreach (var item in getitems()) { ddl1.items.add(new listitem(item.name, item.id.tostring())); } ddl1.items.insert(0, new listitem("make selection")); } 

or even:

private void populate() { getitems().foreach(x => dd1.items.add(new listitem(x.name, x.id.tostring()))); ddl1.items.insert(0, new listitem("make selection")); } 

i.e. add items dropdownlist directly.

in original example, use databinding, there's no need create list of listitem. can databind stuff directly; in instance, code becomes:

private void populate() { dd1.datatextfield = "name"; dd1.datavaluefield = "id" dd1.datasource = getitems(); ddl1.items.insert(0, new listitem("make selection")); } 

i.e. can databind direct list of stuff long tell dropdownlist it's values from. many people prefer model selecteditem stuff, rather string, have object representing item directly. disadvantage viewstate got bigger ;-)


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -