I have a drop down list that is populated with data in the code behind. The DataTextField
attribute is set with the following code:
ddlItems.DataTextField = "ItemName";
I want to display two data properties as the DataTextField
. I tried using the following code but it didn't work. And I have researched on the net but couldn't find how to use two data properties.
ddlItems.DataTextField = "ItemName" + "ItemDescription";
What code do I need to use to do this?
You can use LinqToSql to make a new datasource containing a displayfield which is formatted, the way you want it to be, like:
var datasource = from x in products
select new {
x.Id,
x.Code,
x.Description,
DisplayField = String.Format("{0} ({1})", x.Code, x.Description)
};
comboBox.DataSource = datasource;
comboBox.DataValueField = "Id";
comboBox.DataTextField = "DisplayField";
comboBox.DataBind();
You can use the Formatting event of ddlItems which will allow you to set logic to how to convert a certain item to a string, or if it makes any sense to use in your program, have a property like RepresentingString that returns Name + Desc, and bind to that property.
Similar question with more answers and code examples: Format DropDownList.TextValue
I have done something similar to this in two ways: either in C# or SQL.
Matteo Gaggiano below gives a good example of the C# method:
dataTable.Columns.Add(new DataColumn("Title", System.Type.GetType("System.String"), "ItemName + ' - ' + ItemDescription"));
ddlItems.DataSource = dataTable;
ddlItems.DataTextField = "Title";
ddlItems.DataValueField = "Id";
ddlItems.DataBind();
Or it can be done in SQL:
SELECT ItemName + ' - ' + ItemDescription AS Title FROM yourSQLtable
and then using the last four lines above in the C# code.
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