user4954249
user4954249

Reputation:

Dataset Loading a WPF Combobox

DataSet dataSet = new DataSet();
using (SqlConnection connection = new SqlConnection("server=server;   database=database; user id=user; password=user"))
{
     connection.Open();
     using (SqlCommand command = new SqlCommand("SELECT DISTINCT ID FROM TABLE ORDER BY ID ASC", connection))
     {
          SqlDataAdapter reader = new SqlDataAdapter(command);
          reader.Fill(dataSet);
          IDComboBox.DataContext = dataSet; --> This doesn't work
          IDComboBox.Itemsource = dataSet.Tables[0].Columns[0].ToString() --> doesn't work
          IDComboBox.Itemsource = dataSet.Tables[0].Rows[0].ToString() --> doesn't work
          IDComboBox.Itemsource = dataSet.Tables[0].Rows --> doesn't work
          IDComboBox.Itemsource = dataSet.Tables[0].Columns --> doesn't work
          They don't work even with me pairing it the IDComboBox.DataContext = dataSet.Tables[0].Rows[0] or Columns[0]
     }
     connection.Close();
     connection.Dispose();
}

I am needing to fill my combobox in a WPF with the data from my datatable. All I keep finding are the examples that use Combobox.Displaymember, Combobox.Source to do this but a C# WPF application doesn't have these options. How can I load a WPF combobox with data from a dataset or a datatable?

One way that I was doing it before was

  using (SqlConnection connection = new SqlConnection("server=server; database=database; user id=user; password=user"))
  {
      connection.Open();
      using (SqlCommand command = new SqlCommand("SELECT DISTINCT ID FROM Table ORDER BY ID ASC", connection))
      {
           SqlDataReader reader = command.ExecuteReader();
           while (reader.Read())
           {
               for (int i = 0; i < reader.FieldCount; i++)
               {
                   IDComboBox.Items.Add(reader[i].ToString());
               }
           }
       }
       connection.Close();
       connection.Dispose();
  }

I know having it for looped into my combobox is very slow if I have large amounts of data so I am wanting to dump it in from a dataset to reduce run time.

Upvotes: 3

Views: 2301

Answers (2)

OhBeWise
OhBeWise

Reputation: 5454

Derived from this example, you'll want to work with the ItemSource, DisplayMemberPath, and SelectedValuePath properties:

IDComboBox.ItemsSource = dataSet.Tables[0].DefaultView;
IDComboBox.DisplayMemberPath = dataSet.Tables[0].Columns["ID"].ToString();
IDComboBox.SelectedValuePath = dataSet.Tables[0].Columns["ID"].ToString();

And in xml:

<ComboBox  Name="IDComboBox" ItemsSource="{Binding}"/> 

Upvotes: 1

Sean Beanland
Sean Beanland

Reputation: 1118

The WPF ComboBox has an ItemSource property you can use.

IDComboBox.ItemsSource = dataSet.Tables[0].Rows;

Upvotes: 1

Related Questions