65.9K
CodeProject is changing. Read more.
Home

Displaying Composite Text in DropDown

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.94/5 (15 votes)

Jul 14, 2003

2 min read

viewsIcon

64553

How can you display more then one field in text of the dropdown? Like if you have to display text, which is actually a combination of two fields in the data table. Here is a small tutorial on that.

Introduction

VB.NET eases the job of a programmer to bind data to the dropdown. It is simply a matter of four lines to bind data, You just have to assign some properties of the dropdown and you are done. No loops, nothing!

UserDropDown.DataTextField = "FirstName"
UserDropDown.DataValueField = "UserID"
UserDropDown.DataSource = UserDataSet.Tables(0).DefaultView
UserDropDown.DataBind()

As you all know, it’s a very easy approach to display information in the dropdown. But how about when you have to display more then one field in the text of the dropdown? Like you have to display text which is actually a combination of two fields in the data table.

Creating Composite Text

Let’s take a scenario of the user information system. You have a dropdown in which you want to populate a list of all users. And you want display last name and first name separated by the space (or coma) in the text of the dropdown. How will you do that? Looping to each row of the table and adding to the list item to the dropdown?

Well there is another cleaner ‘way’ to solve this requirement. You just have to add a dynamic data column (with format you want) to the table. And that’s all. Look at the following code sniplet

Dim DynColumn As New DataColumn()
With DynColumn
 .ColumnName = "FullName"
 .DataType = System.Type.GetType("System.String")
 .Expression = "LastName+' '+FirstName"
End With
UserDataSet.Tables(0).Columns.Add(DynColumn)

UserDropDown.DataTextField = "FullName "
UserDropDown.DataValueField = "UserID"
UserDropDown.DataSource = UserDataSet.Tables(0).DefaultView
UserDropDown.DataBind()

Please note that I have set "FullName" column to the DataTextField property of the DropDown instead of other fields of the table. Above code will simply populate drop down with composite text, which is concatenation of field's last name and first name.

If you can notice the last property is set to the dynamic column object. It’s an Expression property of the DataColumn. It will automatically populate the values of the column values based on the expression you have set for that column.

Search your MSDN for "DataColumn.Expression Property" for more explanation about the Expression property. 

Anyway you must have realized the power of the Expression property after reading above article. Using this technique you can easily and dynamically create DataColumn with complex combinations of the data fields.