Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding array + one object to Dropdownlist

I have an array of type Person, which contains string objects: FirstName, LastName, login.

I have this bound to a dropdownlist.

Now along with this array, I also want to display one more item called "Desk". How can i do that?

My current code is:

Person[] traders = GetTraders();
ddl_trader.Items.Clear();
ddl_trader.DataSource = traders;
ddl_trader.DataTextField = "LastName";
ddl_trader.DataValueField = "Login";
ddl_trader.DataBind();

I also want that one extra item I'm adding to be the default selected item.

like image 761
xbonez Avatar asked Jul 27 '26 08:07

xbonez


1 Answers

You can set the AppendDataBoundItems property to true (it's false by default), add your item manually, then do the databinding process to add the remaining items. AppendDataBoundItems determines if the list is cleared during databinding or not.

ddl_trader.Items.Clear();
ddl_trader.AppendDataBoundItems = true;
ddl_trader.Items.Add("Desk");
ddl_trader.DataTextField = "LastName";
ddl_trader.DataValueField = "Login";
ddl_trader.DataSource = traders;
ddl_trader.DataBind();

if you need to add the new item after the list has been bound, you can do

ddl_trader.Items.Insert(0, "Desk");

this does not require setting AppendDataBoundItems to true.

like image 98
lincolnk Avatar answered Jul 29 '26 21:07

lincolnk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!