Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?

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";
like image 825
callisto Avatar asked Jun 17 '09 11:06

callisto


2 Answers

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.

like image 173
Jamie Ide Avatar answered Oct 24 '22 07:10

Jamie Ide


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";
like image 19
Thomas Levesque Avatar answered Oct 24 '22 05:10

Thomas Levesque