动态绑定DataGrid [英] Binding DataGrid Dynamically

查看:77
本文介绍了动态绑定DataGrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button1_Click(object sender, RoutedEventArgs e)
        {
             connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Project/Book.accdb";
            connection = new OleDbConnection(connectionstring);
            sql = "Select*from Authors";
 

 
            DataGrid dg2 = new DataGrid();
 
            
 
          
            try
            {
                connection.Open();
                oledbAdapter = new OleDbDataAdapter(sql, connection);
                oledbAdapter.Fill(dt);
                dg2.DataContext = dt;
                connection.Close();
 

 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
 
            dg2.HorizontalAlignment = HorizontalAlignment.Left;
            dg2.VerticalAlignment = VerticalAlignment.Top;
            dg2.Height = 700;
            dg2.Width = 900;
            dg2.Background = Brushes.YellowGreen;
            grid1.Children.Add(dg2);
           
 
        }



此代码实例化一个DataGrid dg2,并期望显示数据库书的内容.但只显示一个空白的DataGrid表单.我必须在某个地方执行DataBinding,以及如何在后面的代码中做到这一点.



this code instantiate a DataGrid dg2 and expected to show the content of Database Book . but only a Blank DataGrid form is shown. somewhere i have to do the DataBinding and how I can do it in the codebehind.

Any help will be appreaciated

推荐答案

您好,Mr.MohammadIqbal,

您请写一个声明
dg2.ItemsSource = dt.DefaultView; 而不是dg2.DataContext = dt;

-
享受吧.
Hi Mr.MohammadIqbal,

You pls write a statement
dg2.ItemsSource = dt.DefaultView; instead of dg2.DataContext = dt;

--
Enjoy.


这篇关于动态绑定DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆