views:

1918

answers:

7

Id like to bind a combo to a datatable (which I cannot alter ito it original schema)

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

What I want to do, is have the combo textfield show tbldata.Name column + 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";
A: 

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
+2  A: 

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
i agree, can't think of another way
AlexDrenea
Since this is a simple one-use only, using a class as a base for this is overkill.
callisto
I meant if a class is already being used.
Rashmi Pandit
+2  A: 

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
I like this a lot better than the suggestions people keep making about modifying the data object and creating a new property.
TheTXI
+1  A: 

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

Ajw
A: 

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
+4  A: 

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 (var 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.

Jamie Ide
Just what I needed thanks.
callisto
A: 

Or implement 'Format' event like this:

DataRow r = ((DataRowView)e.ListItem).Row;
e.Value = r[ "FirstName" ] + " - " + r[ "LastName" ];
signetro