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.
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();
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With