I am creating a anonymous type list using LINQ, and later binding it with a ComboBox. But I want to add an empty item in that list, but its not working.
XNamespace ns = xDocItems.Root.Name.Namespace;
var items =
from i in
xDocItems.Descendants(ns + "insync_navpaymentmethods")
select new
{
code = (string)i.Element(ns + "Code"),
};
Here I am creating anonymous type list from a XElement using LINQ.
items.ToList().Insert(0, new { code = string.Empty });
//items.ToList().Add(new { code = string.Empty }); //Not working
Adding a Blank Item in this list. So a Blank item can be selected by user in combo box.
cmbPaymentMethods.DataSource = items.ToList();
cmbPaymentMethods.DisplayMember = "code";
cmbPaymentMethods.ValueMember = "code";
I shall thankful for any advice.
Kishore
I strongly suspect this builds but doesn't show the extra item. That's because you're adding the new item to a "temporary" list that you throw away, and then you're building a new list for the data source.
You want to call ToList()
just once, and use that list for both insertion and the data source:
var itemsList = items.ToList();
itemsList.Insert(0, new { code = string.Empty }); // Or use Add for the end...
cmbPaymentMethods.DataSource = itemsList;
See more on this question at Stackoverflow