I'm binding combobox to a DataTable (table columns are "NAME", "SURNAME" and "ID"). Currently I have set ValueMember to "ID", and DisplayMember to "SURNAME". I wish to change DisplayMember - and DisplayMember only. By reading all sorts of documentation (including this forum) It can be achieved by exposing a custom property and bind combobox to that, however I'm having difficulties with It.
Closest solution was found
So I tried with this:
private string _employee;
public string MyDisplay
{
get
{
DataRowView r = (DataRowView)this.SelectedItem;
DataRow s = r.Row;
return _employee= s["SURNAME"].ToString() + " " + s["NAME"].ToString();
}
set
{
this._employee = value;
}
}
But that doesn't display my custom DisplayMember when I bind It to MyDisplay, when I scroll combobox Items It's Text is only System.Data.DataRowView.
What is the correct way to accomplish this ?
EDIT:
My full code for binding comboboxes:
private void FillCombobox()
{
var dt = new DataTable();
try
{
using (var conn = new OracleConnection(conn_string))
{
using (OracleCommand cmd = new OracleCommand("MYSCHEMA.EMPLOYEES"))
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("CHOOSE_SELECT_IN", OracleDbType.Decimal, 6, ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter("RESULT_OUT", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
using (OracleDataAdapter da = new OracleDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(dt);
}
//bind combobox
BindData(dt, Combobox1, "MyDisplay", "ID");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void BindData(DataTable dt, ComboBox ctl, string displayMember, string valueMember)
{
if (ctl.InvokeRequired)
{
ctl.Invoke(new Action<DataTable, ComboBox, string, string>(BindData),
dt,
ctl,
displayMember,
valueMember);
}
else
{
ctl.DisplayMember = displayMember;
ctl.ValueMember = valueMember;
ctl.DataSource = dt;
ctl.Text = "";
ctl.SelectedIndex = -1;
}
}
Looks like there is one simple, one line mehod to do that, no property of any kind required. Just a simple add of calculated column to a Datatable in a place where you bind Combobox, and then you just set that column as DiplayMember. So my solution to all problem follows as this:
//Add calculated column to Datatable and set this column to DiplayMember
dt.Columns.Add("MyDisplay", typeof(string),"SURNAME + " " + NAME");
So, It's an easy one. I even included settings for display in .config, so I can change combobox DisplayMember to whatever I like. Neat solution 🙂