简体   繁体   中英

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.

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}"/> 

WPF ComboBox具有您可以使用的ItemSource属性。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM