Question

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

Was it helpful?

Solution

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;

OTHER TIPS

items.ToList() will return a new instance of the object, so the item is being added into a new list, which is not the one you want.

Everytime you have "items.ToList()" a new instance will be created. You would need to have:

var list =  items.ToList();

list.Add(new { code = string.Empty });

cmbPaymentMethods.DataSource = list;

how to use XNamespace ns = xDocItems.Root.Name.Namespace; var items = from i in xDocItems.Descendants(ns + "insync_navpaymentmethods") select new { code = (string)i.Element(ns + "Code"),

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top