Gergő Bakonyi
Gergő Bakonyi

Reputation: 37

Binding DataSet to a ComboBox in WPF

I've a problem. I'm not a WPF master, but I've a homework to complete.

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. :)

If you would help me, that would be great.

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#:

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:

https://i.sstatic.net/1XgYS.png

Upvotes: 1

Views: 17619

Answers (2)

ocuenca
ocuenca

Reputation: 39326

If the name of your columns are "description" and "type_id" you can just do this:

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:

 category_select.ItemSource= ds.Tables["t"].DefaultView;

So, you don't have to set that property (ItemSeource) in your view:

 <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.

Upvotes: 7

safi
safi

Reputation: 879

category_select.ItemsSource = ds.Tables["t"].DefaultView;
category_select.DisplayMemberPath = "description";
category_select.SelectedValuePath = "type_id";

Upvotes: 1

Related Questions