How to use combo box in C #

I don't know where to start. i tried DataTable but it didn't work. (This is a simple question :))

I tried everything

{
    var test = new DataTable();
    test.Columns.Add("test");
    test.TableName = "test";
    test.Columns.Add("test");

    comboBox1.DataSource = test.XXXX ;

}

      

+2


source to share


4 answers


Assuming you mean winforms, something like:

    DataTable test = new DataTable();
    test.TableName = "test";
    test.Columns.Add("foo", typeof(string));
    test.Columns.Add("bar", typeof(int));
    test.Rows.Add("abc", 123);
    test.Rows.Add("def", 456);

    ComboBox cbo = new ComboBox();
    cbo.DataSource = test;
    cbo.DisplayMember = "foo";
    cbo.ValueMember = "bar";

    Form form = new Form();
    form.Controls.Add(cbo);
    Application.Run(form);

      



(in particular SelectedValue

should provide you with 123

and 456

- useful for ids, etc.)

+6


source


ComboBox.Items property if you don't need data from database or something.



+2


source


  DataTable dt=new DataTable();
  dt.Columns.Add("Col1",typeof(int));
  dt.Columns.Add("Col2",typeof(String));
  dt.Rows.Add(1,"A");
  dt.Rows.Add(2,"B");

   comboBox1.DataSource = dt;
   comboBox1.DisplayMember = "Col2";
   comboBox1.ValueMember = "Col1";

      

+2


source


You need to set "DataItemField" and "DataValueField" to the corresponding column names in your datatable.

+1


source







All Articles