ktos1234
ktos1234

Reputation: 207

Two field values in Combobox displaymember and datatable C#

I want to bind two fields together and display it in combobox.

I have first name and last name in my database, how to display full name in combobox?

I tried this code but I got some errors:

OracleDataAdapter names= new OracleDataAdapter("SELECT first, last FROM person", conn);
DataTable dt = new DataTable();
names.Fill(dt);
dt.Columns.Add("FullName", typeof(string), "first' : ' last"); //<-- error's here
cmbCBox.DisplayMember = "FullName";
cmbBox.DataSource = dt;
conn.Close();

Error is :

Missing operand after ':' operator.

Upvotes: 1

Views: 2114

Answers (2)

Steve
Steve

Reputation: 216293

Simply ask the database engine to create your FullName for you

// Oracle operator to concatenate strings is || 
string query = @"SELECT first || ' ' || last as FullName FROM person";
OracleDataAdapter names= new OracleDataAdapter(query, conn);
...
cmbCBox.DisplayMember = "FullName";

This approach will return just the FullName as a composite of first and last fields. Of course nothing prevents you to add other fields if you need them. For example you could need the PersonID (or whatever is the primary key on the person table) to use for the ValueMember of your combo. In that way you could read the SelectedValue to recover the Person record belonging to the selected FullName.

A final note. I think that building client side the FullName using the DataTable expression is a good choice for many scenarios but not in this context where the Database engine could do it a lot faster. I suggest to make a simple check using a stopwatch to verify the differences.

Upvotes: 1

Robin Mackenzie
Robin Mackenzie

Reputation: 19319

If you want to create a format like this:

Donald : Duck

Then the expression is:

dt.Columns.Add("full", typeof(string), "first + ' : ' + last");

Example code:

System.Data.DataTable dt = new System.Data.DataTable();

dt.Columns.Add("first", typeof(string));
dt.Columns.Add("last", typeof(string));
dt.Columns.Add("full", typeof(string), "first + ' : ' + last");

System.Data.DataRow row = dt.NewRow();
row["first"] = "Donald";
row["last"] = "Duck";
dt.Rows.Add(row);

Upvotes: 1

Related Questions