开发者

Binding array + one object to Dropdownlist

开发者 https://www.devze.com 2023-01-20 10:18 出处:网络
I have an array of type Person, which contains string objects: FirstName, LastName, login. I have this bound to a 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开发者_如何学C?

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.


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.


One such method is to load the result of GetTraders() into a List<Person>. You can then add one or many new Person objects to the list before binding it to your dropdown.

List<Person> traders = new List<Person>(GetTraders());
traders.Add(new Person() { LastName = "Foo", Login = "Bar" });
ddl_trader.DataSource = traders;

You could also define an additional array and concatenate that to the result instead of creating a combined collection. (Note: this would be two distinct arrays treated as a single sequence, however the backing arrays would still be seperate).

Person[] traders = GetTraders();
Person[] moreTraders = new Person[] { new Person() { LastName = "Foo", Login = "Bar" } };
ddl_trader.DataSource = traders.Concat(moreTraders);
0

精彩评论

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

关注公众号