Reputation: 25
As the title suggests, I'm trying to fill a ListBox
with the results of a db query, though I'm not sure how to manage this. I've managed to populate a DataGrid
from another query, but I'm not sure how to do the same with a ListBox
. I'm sure it's simple, but I'm missing something! Similar overflow pages/google searches haven't yet yielded a clear answer. I'm using c# in a WPF app in visual studio.
In a separate class I have this:
public DataTable FillAllMenuItems()
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DustCatcher\Documents\pizzeria.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand("SELECT name FROM MenuItems", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Menu Items");
sda.Fill(dt);
return dt;
}
As an aside, I'm sure the above is messy so any pointers there would be great (do I need a using
anywhere there?). On the relevant window cs file I have:
User user = User.GetInstance();
lstbxAllItems.ItemsSource = user.FillAllMenuItems().DefaultView;
Running the app, the ListBox
has System.Data.DataRowView
as many times as there are items in the database. Where am I going wrong?
Upvotes: 2
Views: 1891
Reputation: 33
private void BindListbox()
{
myListBox.DataSource = dt;
myListBox.DisplayMemberPath = "Name";
}
Upvotes: 1
Reputation: 39976
You need to set lstbxAllItems.DisplayMemberPath
after lstbxAllItems.ItemsSource
:
lstbxAllItems.DisplayMemberPath = "Name"; // Or any column you want to show in your ListBox
But as a better approach you can use ListView.ItemTemplate
and Binding
for this purpose. Something like this:
<ListBox Name="lstbxAllItems">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Upvotes: 2