0

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.