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?
ValueMemberPathandDisplayMemberPathof yourListBoxalso I would recommend to useusingstatements for yourSqlConnection, SqlCommandetc. Link for theItemSourcestackoverflow.com/questions/1790878/…