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();
}
我需要用我的数据表中的数据填充WPF中的组合框。我一直在寻找的是使用Combobox.Displaymember,Combobox.Source来做这个的例子,但C#WPF应用程序没有这些选项。如何使用数据集或数据表中的数据加载WPF组合框?
我以前做过的一种方式是
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();
}
我知道如果我有大量的数据,那么循环进入我的组合框非常慢,所以我想从数据集中转储它以减少运行时间。
答案 0 :(得分:2)
来自this example,您需要使用ItemSource
,DisplayMemberPath
和SelectedValuePath
属性:
IDComboBox.ItemsSource = dataSet.Tables[0].DefaultView;
IDComboBox.DisplayMemberPath = dataSet.Tables[0].Columns["ID"].ToString();
IDComboBox.SelectedValuePath = dataSet.Tables[0].Columns["ID"].ToString();
在xml
:
<ComboBox Name="IDComboBox" ItemsSource="{Binding}"/>
答案 1 :(得分:1)
WPF ComboBox
具有您可以使用的ItemSource属性。
IDComboBox.ItemsSource = dataSet.Tables[0].Rows;