How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?
Solution 1
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.
Solution 2
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";
Solution 3
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();
Solution 4
Or implement 'Format' event like this:
DataRow r = ((DataRowView)e.ListItem).Row;
e.Value = r[ "FirstName" ] + " - " + r[ "LastName" ];
Solution 5
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.
Related videos on Youtube
Comments
-
callisto about 4 years
I'd like to bind a
ComboBox
to aDataTable
(I cannot alter its original schema)cbo.DataSource = tbldata; cbo.DataTextField = "Name"; cbo.DataValueField = "GUID"; cbo.DataBind();
I want the
ComboBox
showtbldata.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";
-
AlexDrenea almost 15 yearsi agree, can't think of another way
-
TheTXI almost 15 yearsI like this a lot better than the suggestions people keep making about modifying the data object and creating a new property.
-
callisto almost 15 yearsSince this is a simple one-use only, using a class as a base for this is overkill.
-
Konstantinos Chertouras about 8 yearsMost useful ! Thanks.
-
TangMonk about 4 yearsWhere is the Format event?
-
jlear about 4 years@TangMonk, the Format event is in the ComboBox class. See here: ComboBox