views:

45

answers:

2

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.

+1  A: 

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);
Anthony Pegram
I was wondeing if it could be done without adding it to the list. Since, it is really just a string "Desk" and doesn't need a FirstName, Lastname etc.
xbonez
Gotcha. If I can't figure out a way to do it without creating another array of Person class, I'll use your second method.
xbonez
For some reason, traders.Concat returns an error. Is there some assembly or reference I need to use Concat?
xbonez
@xbonez, It's an extension method of `IEnumerable<T>` from .NET 3.5+, C# 3.0+. If you are on a compatible platform (think: Visual Studio 2008 or 2010), you'd need a reference to System.Core.dll and a `using System.Linq;` statement in your code-behind. If you are on a prior version of .NET, try the first approach (VS 2005+, `using System.Collections.Generic;`).
Anthony Pegram
+1  A: 

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.

lincolnk
Just what I wanted. Thanks!
xbonez