0
votes

Now when i press the Button the data doesn't show up in the List box , any help ? i want to get the data from database and show it in a list box , so the user can select items from it. i'm using WPF and SQL server 2008 R2 ..

private void button1_Click(object sender, RoutedEventArgs e) {

        SqlConnection myConnection = new SqlConnection("user id=userid;" +
                                   "password=password;server=localhost;" +
                                   "Trusted_Connection=yes;" +
                                   "database=db1; " +
                                   "connection timeout=30");

        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        try
        {
            myConnection.Open();

        }
        catch (Exception ex)
        {
            textBlock1.Text = "" + (ex.ToString());
        }

        da.SelectCommand = new SqlCommand("Select * FROM Products", myConnection);
        da.Fill(ds,"Products");
        listBox1.DataContext = ds;

    }
2

2 Answers

1
votes

Firstly, its probably easier to bind to the itemsSource rather than the datacontext

Secondly, you're trying to bind your listbox directly to a dataset, which i don't think is possible. I would create a dataview property and set that to ds.Tables[0].DefaultView. Then in your listbox xaml code to show the columns put:

<ListView ItemsSource="{Binding Path=myDataViewProperty}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Column1"  DisplayMemberBinding="{Binding Column1}"/>
            <GridViewColumn Header="Column2" DisplayMemberBinding="{Binding Column2}"/>
        </GridView>
    </ListView.View>
</ListView>

thirdly, are you sure a listbox is the most suitable control for what you wish to display? the datagrid may be a better choice.

1
votes

You have to define your bindings, setting the DataContext alone doesn't fill the data, it just declares the source where the bound data comes from.

<ListBox ItemsSource="{Binding Tables[0]}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding ProductName}"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

or if you just want to display a single value in your listbox:

<ListBox ItemsSource="{Binding Tables[0]}" DisplayMemberPath="ProductName"/>