将数据集绑定到 WPF 中的组合框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27760385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding DataSet to a ComboBox in WPF
提问by Gerg? Bakonyi
I've a problem. I'm not a WPF master, but I've a homework to complete.
我有问题。我不是 WPF 高手,但我有作业要完成。
I'm trying to bind my dataset from my database to a combobox.
我正在尝试将我的数据集从我的数据库绑定到一个组合框。
I've done this in Windows Form Application, but I don't know how to in WPF. I've searched across the whole internet, but I'm a kind of slow person. :)
我已经在 Windows 窗体应用程序中完成了此操作,但我不知道如何在 WPF 中执行此操作。我在整个互联网上搜索过,但我是一个行动缓慢的人。:)
If you would help me, that would be great.
如果你能帮助我,那就太好了。
XAML:
XAML:
<StackPanel>
<TextBlock Text="Válassz kategóriát!" FontSize="18" FontFamily="Capture it" HorizontalAlignment="Center"></TextBlock>
<ComboBox Name="category_select" ItemsSource="{Binding}"></ComboBox>
</StackPanel>
C#:
C#:
private void show_categories()
{
category_select.Items.Clear();
SqlConnection con = new SqlConnection("Data Source=HQ\SQLEXPRESS;Initial Catalog=BGIQuiz;Integrated Security=True");
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
try
{
SqlDataAdapter category_data = new SqlDataAdapter("SELECT * FROM TYPE", con);
DataSet ds = new DataSet();
category_data.Fill(ds, "t");
category_select.DataContext = ds.Tables["t"].DefaultView;
category_select.DisplayMemberPath = ds.Tables["t"].Columns["description"].ToString();
category_select.SelectedValuePath = ds.Tables["t"].Columns["type_id"].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Database:
数据库:


回答by octavioccl
If the name of your columns are "description" and "type_id" you can just do this:
如果您的列名称是“description”和“type_id”,您可以这样做:
category_select.DisplayMemberPath = "description";
category_select.SelectedValuePath = "type_id";
As a suggestion, you could set the ItemSource property instead the DataContext in your code begind:
作为建议,您可以在代码开始时设置 ItemSource 属性而不是 DataContext :
category_select.ItemSource= ds.Tables["t"].DefaultView;
So, you don't have to set that property (ItemSeource) in your view:
因此,您不必在视图中设置该属性 (ItemSeource):
<ComboBox Name="category_select"></ComboBox>
Also you can do this:
你也可以这样做:
<ComboBox Name="category_select" DisplayMemberPath = "description" SelectedValuePath = "type_id"></ComboBox>
And don't set those properties in your code behind.
并且不要在后面的代码中设置这些属性。
回答by safi
category_select.ItemsSource = ds.Tables["t"].DefaultView;
category_select.DisplayMemberPath = "description";
category_select.SelectedValuePath = "type_id";

