Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Two Fields to Display in Dropdown List

I am trying to concatenate two fields from a list to display in a dropdown. Below is the code i am trying to use. I don't want to change the model of my products so I was trying to do something like that below but I can't figure anything out without building out my own object with the fields concatenated.

            skuDropDown.DataSource = List<product>
            skuDropDown.DataTextField = "ProductId" // want to combine with"Description";
            skuDropDown.DataValueField = "ProductId";
            skuDropDown.DataBind();

Thanks any ideas will help.

like image 497
Locke12 Avatar asked May 26 '10 20:05

Locke12


3 Answers

To assign the source with your given method, I would go for using LINQ to create an anonymous type with the properties you want. Something like

List<Product> products = new List<Product>();
products.Add(new Product() { ProductId = 1, Description = "Foo" });
products.Add(new Product() { ProductId = 2, Description = "Bar" });

var productQuery = products.Select(p => new { ProductId = p.ProductId, DisplayText = p.ProductId.ToString() + " " + p.Description });

skuDropDown.DataSource = productQuery;
skuDropDown.DataValueField = "ProductId";
skuDropDown.DataTextField = "DisplayText";
skuDropDown.DataBind();
like image 175
Anthony Pegram Avatar answered Sep 24 '22 10:09

Anthony Pegram


IF you have a class to represent a product, just create a property that extend your class and return it combined, for example:

        public string ID_Description {
            get 
            {
               return string.Format("{0} ({1})", Name, ProductId);
            }
        }

and, in your databind dropdown reference your property

skuDropDown.DataSource = productQuery;     
skuDropDown.DataValueField = "ProductId";     
skuDropDown.DataTextField = "ID_Description";     
skuDropDown.DataBind(); 
like image 34
Diego Mendes Avatar answered Sep 25 '22 10:09

Diego Mendes


You can do this:

List<Product>.ForEach(
  x => skuDropDown.Items.Add(
    new Item(x.ProductId + " " x.ProductDescription, x.ProductId)
 );

Just loop through the list and add each item to the drop down list. It's what .net will do for you behind the scenes in your example.

like image 37
kemiller2002 Avatar answered Sep 23 '22 10:09

kemiller2002