Athiwat Chunlakhan
Athiwat Chunlakhan

Reputation: 7809

How to use combo box in c#

I have no idea where to start. i tried DataTable but it didn't work.(This is an easy question :) )

I tried everything

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

    comboBox1.DataSource = test.XXXX ;

}

Upvotes: 2

Views: 3376

Answers (4)

KV Prajapati
KV Prajapati

Reputation: 94653

  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";

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1064184

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 give you the 123 and 456 - useful for ids, etc)

Upvotes: 6

Matthew Iselin
Matthew Iselin

Reputation: 10670

ComboBox.Items property, unless you want data from a database or something.

Upvotes: 2

Noon Silk
Noon Silk

Reputation: 55172

You'll need to set the 'DataItemField' and 'DataValueField' to the appropriate column names in your datatable.

Upvotes: 1

Related Questions