Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set drop down list DataTextField to display two data property fields?

Tags:

c#

asp.net

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?

like image 842
Theomax Avatar asked Mar 23 '12 10:03

Theomax


3 Answers

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();
like image 130
Kris Senden Avatar answered Oct 13 '22 19:10

Kris Senden


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

like image 7
SimpleVar Avatar answered Oct 13 '22 20:10

SimpleVar


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.

like image 4
Davezilla Avatar answered Oct 13 '22 19:10

Davezilla