【发布时间】:2016-03-12 06:44:57
【问题描述】:
正如标题所示,我正在尝试用数据库查询的结果填充ListBox,但我不确定如何管理它。我已经设法从另一个查询中填充了DataGrid,但我不确定如何对ListBox 做同样的事情。我敢肯定这很简单,但我错过了一些东西!类似的溢出页面/谷歌搜索尚未产生明确的答案。我在 Visual Studio 的 WPF 应用程序中使用 c#。
在一个单独的课程中,我有这个:
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;
}
顺便说一句,我确信上面的内容很混乱,所以那里的任何指针都会很棒(我需要using 吗?)。在相关的窗口 cs 文件中,我有:
User user = User.GetInstance();
lstbxAllItems.ItemsSource = user.FillAllMenuItems().DefaultView;
运行应用程序时,ListBox 拥有 System.Data.DataRowView 的次数与数据库中的项目数一样多。我哪里错了?
【问题讨论】:
-
设置
ValueMemberPath和DisplayMemberPath的ListBox我也建议为SqlConnection, SqlCommand等使用using语句。ItemSource的链接stackoverflow.com/questions/1790878/…跨度> -
Displaymemberpath 做到了 - 感谢您的评论!
-
@user2946329 感谢简洁的课程。