1

I have an employee table. I want the combobox to present the employee number and city.

SqlCommand cmd = new SqlCommand();
Connection c = new Connection();
cmd.CommandText = "SELECT employeeNumber, city FROM tblEmployee";

SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Employee");

comboBox1.DataSource = ds;

That's what I got so far, can anyone help me with that?

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
user2023203
  • 546
  • 1
  • 12
  • 19

3 Answers3

2

You can add a Format event to your ComboBox, and in it compose whatever it is you want to show:

private void _Combobox1_Format(object sender, ListControlConvertEventArgs e)
{
    var x = (DateFilterType)e.ListItem;
    e.Value = /* insert string concatenation stuff here... */;
}
Jonathan
  • 6,939
  • 4
  • 44
  • 61
1

you can override .ToString() on the class you're binding to the combobox.

class MyClass
{
    public override string ToString()
    {
        return thing1.PadRight(10) + thing2.PadRight(10);
    }
    public string thing1 { get; set; }
    public string thing2 { get; set; }
}

Then if you do something like

List<MyClass> mc = new List<MyClass>();
mc.Add(new MyClass() { thing1 = "blah1", thing2 = "blah2});

comboBox1.DataSource = mc;

the text which is displayed in comboBox1 is blah1 blah2 (we'll the formatting here is knocking off all my spaces but these strings are supposed to be padded)

and you use whatever value you want from your class as such

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
   label1.Text = ((MyClass)comboBox1.SelectedItem).ToString();
}

without having to set a value member

Brad
  • 11,934
  • 4
  • 45
  • 73
0

In the datatable you, use add a third column with an expression. In this last column do the concatenation of the two other column.

check this for expression reference.

After this use this third column to bind your combobox.

Rémi
  • 3,867
  • 5
  • 28
  • 44
  • @user2023203 I think this [link here on SO](http://stackoverflow.com/questions/14643808/datacolumn-expression-to-concat-columns-returning-empty) is pretty mutch the same thing as you – Rémi Aug 07 '13 at 15:45
  • @Brad i never talked about modifying the database... I talked about the datatable – Rémi Aug 07 '13 at 16:39