【问题标题】:How can I bind a listbox to a data table in WPF applications/如何将列表框绑定到 WPF 应用程序中的数据表/
【发布时间】:2021-01-09 04:02:45
【问题描述】:

我正在尝试将一列表的内容放入listbox。我使用此代码来执行此操作。

listBox1.DataContext = ds.Tables[0];

我也试过用这段代码

listBox1.ItemsSource = ds.Tables[0];

两者都不起作用。

知道我该怎么做吗?

    namespace itinventory
    {
       /// <summary>
      /// Interaction logic for MainWindow.xaml
      /// </summary>
     public partial class MainWindow : Window
     {
         SqlConnection con ;
         SqlDataAdapter da ;
         DataSet ds;

        public MainWindow()
        {
            InitializeComponent();
            con = new SqlConnection("Server=myserver\\sqlexpress;" + "Database=ITINVENTORY;User ID=sa;" + "Password=mypassword");
            con.Open();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SqlDataAdapter da = new SqlDataAdapter("select DISTINCT orgcode from Employees", con);
            DataSet ds = new DataSet();
            da.Fill(ds,"orgcode");
            listBox1.DataContext = ds.Tables[0];
        }
    }
}    

【问题讨论】:

    标签: wpf binding listbox


    【解决方案1】:

    这里是优化的代码和一些建议。

    string constring = @"Data Source=.\SQLEXPRESS;AttachDbFilename='D:\TEMPX\Projects X\ODataClient\ODataClient\Data\northwnd.mdf';Integrated Security=True;User Instance=True";
            void button1_Click(object sender, RoutedEventArgs e)
            {
                DataTable dt = new DataTable();
                using (SqlConnection con = new SqlConnection(constring))
                {
                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter("select * from Employees", con);
    
                    da.Fill(dt);
                    con.Close();
                }
    
                listBox1.ItemsSource = dt.AsDataView();
            }
    

    我不会告诉你如何编写查询。但是对于您的问题,这里有几点。

    如果您使用绑定,那么 dataContext 就可以了。 DataContext 意味着您正在传递一个可以进一步绑定到其子属性的对象。并且您需要绑定 ListBox 的 ItemsSource 属性。作为

    ItemsSource={Binding}。

     <ListBox x:Name="listBox1">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding FirstName}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
    

    但是,如果您只是将数据传递给 List,您需要做的就是将数据分配到 ItemsSource 属性中,这只会显示对象类型的全名,而不是显示数据。使用上面的模板展示数据。

    另一件事是,当您将 DataTable 对象分配给 itemsssource/DataContext 时,源必须是 Enumrable,因此将其用作 DataView。它继承自 Ilist , IEnumrable。等等

    【讨论】:

    • 谢谢。它工作得很好。我不清楚。这就是为什么我必须学习更多,然后回来检查,你是完美的!
    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 2013-07-08
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    相关资源
    最近更新 更多