将数据集绑定到列表框

发布于 01-04 03:24 字数 519 浏览 2 评论 0原文

我想将 SQL 查询的结果绑定到 WPF 界面的列表框。正如我见过的许多例子一样,我无法调整我的应用程序以使其正常工作。我在后面使用此代码:

string sqlStr1 = "SELECT Players.LastName FROM Players";

SqlDataAdapter dAdapt1 = new SqlDataAdapter(sqlStr1, cnStr);
DataSet dataSet1 = new DataSet();
dAdapt1.Fill(dataSet1);

List1.DataContext = dataSet1;

并在 xaml 页面中:

<ListBox Name="List1" Grid.Column="1" Grid.Row="2" ></ListBox>

绑定它们以便名称出现在列表框中的方法是什么?

如果没有在 xaml 页面中添加任何 Binding,当我尝试运行它时它会抛出异常。怎么了?

I want to bind the results of an SQL query to a Listbox of an WPF interface. As many examples I have seen, I cannot tweak my application, so as to work properly. I use this code behind:

string sqlStr1 = "SELECT Players.LastName FROM Players";

SqlDataAdapter dAdapt1 = new SqlDataAdapter(sqlStr1, cnStr);
DataSet dataSet1 = new DataSet();
dAdapt1.Fill(dataSet1);

List1.DataContext = dataSet1;

and in the xaml page:

<ListBox Name="List1" Grid.Column="1" Grid.Row="2" ></ListBox>

What is the way to bind them so as the name to appear in the Listbox?

Without adding any Binding in the xaml page, it throws an exceprtion when I try to run it. What is wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦断已成空2025-01-11 03:24:49

您的项目源未设置。

您可以这样做:

 List1.ItemsSource= dataSet1.Tables["Players"]; //instead of List1.DataContext = dataSet1;

或者

 List1.DataContext = dataSet1.Tables["Players"];
 <ListBox Name="List1" ItemsSource="{Binding}" Grid.Column="1" Grid.Row="2" >
  <ListBox.ItemTemplate>
   <DataTemplate>
    <TextBlock Text="{Binding LastName}"/>
   </DataTemplate>
  </ListBox.ItemTemplate>
 </ListBox>

将姓氏假定为列名。顺便说一句,所有代码都是手写的,所以可能会有一些错误:)

your itemssource is not set.

you can do:

 List1.ItemsSource= dataSet1.Tables["Players"]; //instead of List1.DataContext = dataSet1;

or

 List1.DataContext = dataSet1.Tables["Players"];
 <ListBox Name="List1" ItemsSource="{Binding}" Grid.Column="1" Grid.Row="2" >
  <ListBox.ItemTemplate>
   <DataTemplate>
    <TextBlock Text="{Binding LastName}"/>
   </DataTemplate>
  </ListBox.ItemTemplate>
 </ListBox>

the LastName is assumed as the Columnname. btw all code is just handwritten, so there may be some errors :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文