25

I'd like to bind a ComboBox to a DataTable (I cannot alter its original schema)

cbo.DataSource = tbldata;
cbo.DataTextField = "Name";
cbo.DataValueField = "GUID";
cbo.DataBind();

I want the ComboBox show tbldata.Name + tbldata.Surname.

Of course adding the new name+surname as a field to the tbldata just before binding is possible, but I am hoping for a more elegant solution along the lines of (pseudocode)

cbo.DataTextField = "Name";
cbo.DataTextField += "Surname";
Breeze
  • 2,010
  • 2
  • 32
  • 43
callisto
  • 4,921
  • 11
  • 51
  • 92

7 Answers7

26

The calculated column solution is probably the best one. But if you can't alter the data table's schema to add that, you can loop through the table and populate a new collection that will serve as the data source.

var dict = new Dictionary<Guid, string>();
foreach (DataRow row in dt.Rows)
{
    dict.Add(row["GUID"], row["Name"] + " " + row["Surname"]);
}
cbo.DataSource = dict;
cbo.DataTextField = "Value";
cbo.DataValueField = "Key";
cbo.DataBind();

Obviously this isn't as performant as binding directly to the DataTable but I wouldn't worry about that unless the table has thousands of rows.

Michael Eakins
  • 4,149
  • 3
  • 35
  • 54
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
19

The easiest way is to create a new calculated column in the DataTable, using the Expression property :

tbldata.Columns.Add("FullName", typeof(string), "Name + ' ' + Surname");
...
cbo.DataTextField = "FullName";
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    I like this a lot better than the suggestions people keep making about modifying the data object and creating a new property. – TheTXI Jun 17 '09 at 12:10
5

I would create a property on your data object then map that to the DataTextField

Data Object

public string FullName
{
  get { return Name + " " + Surname; }
}

Code-behind

cbo.DataSource = tbldata;
cbo.DataTextField = "FullName";
cbo.DataValueField = "GUID";
cbo.DataBind();
bendewey
  • 39,709
  • 13
  • 100
  • 125
5

Or implement 'Format' event like this:

DataRow r = ((DataRowView)e.ListItem).Row;
e.Value = r[ "FirstName" ] + " - " + r[ "LastName" ];
anaconda
  • 1,065
  • 10
  • 20
2

Have a property in your class that is the concat of Name and Surname. And bind the DataTextField to this property.

In case you are binding it to a DataTable, you can add a new column to the DataTable whose values are concat of Name and Surname and bind it to the combo.

Rashmi Pandit
  • 23,230
  • 17
  • 71
  • 111
1

Have a look at calculated columns using the Expression property of DataColumn.

Ajw
  • 716
  • 3
  • 8
0

You can register the combo binding event and iterate the items, setting each item text to the desired fields using the combobox item data item.

Tamir
  • 3,833
  • 3
  • 32
  • 41