【问题标题】:Fill ListBox with db query results用数据库查询结果填充 ListBox
【发布时间】: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 的次数与数据库中的项目数一样多。我哪里错了?

【问题讨论】:

  • 设置ValueMemberPathDisplayMemberPathListBox 我也建议为SqlConnection, SqlCommand 等使用using 语句。ItemSource 的链接stackoverflow.com/questions/1790878/…跨度>
  • Displaymemberpath 做到了 - 感谢您的评论!
  • @user2946329 感谢简洁的课程。

标签: c# wpf database listbox


【解决方案1】:
private void BindListbox() 
{
    myListBox.DataSource = dt;
    myListBox.DisplayMemberPath = "Name";
}

【讨论】:

  • 感谢您的回答,虽然我想在陷入困境之前避免使用其他方法!
  • 在 WPF 中 DisplayMember 应该是 DisplayMemberPath。请编辑您的答案并将其更改为DisplayMemberPath
【解决方案2】:

你需要在lstbxAllItems.ItemsSource之后设置lstbxAllItems.DisplayMemberPath

lstbxAllItems.DisplayMemberPath = "Name"; // Or any column you want to show in your ListBox

但作为一种更好的方法,您可以为此目的使用ListView.ItemTemplateBinding。像这样的:

<ListBox Name="lstbxAllItems">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

【讨论】:

  • 非常感谢,添加 displaymemberpath 成功了!我会详细了解您建议的替代方法,因为我不太确定如何正确实施它!
猜你喜欢
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
相关资源
最近更新 更多