WPF C#将DataTable绑定到DataGrid的两种方法

方法一:前台+后台

前台设置如下:

<DataGrid x:Name="StaffAdminView" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="294" VerticalAlignment="Top" Width="347" Margin="30,83,0,0">

注意一定要有ItemsSource="{Binding}"

后台设置如下:

string sql = @"Select * from Staff";
DataSet ds = new DataSet(); 
SqlDataAdapter da = new SqlDataAdapter(sql, connection);                
da.Fill(ds,"Staff");
StaffAdminView.DataContext = ds.Tables["Staff"];  //设置DataGrid的DataContext属性的table

方法二:只有后台

代码如下

string sql = @"Select * from Staff";
DataSet ds = new DataSet(); 
SqlDataAdapter da = new SqlDataAdapter(sql, connection);                
da.Fill(ds,"Staff");
DataView dv = new DataView(ds.Tables["Staff"]);  创建DataView的实例dv,并指定其table
StaffAdminView.ItemsSource = dv;  //设置DataGrid的ItemsSource属性

 消除最后的空列:

在你最后一列的定义上,加上Width ="*" 就可以了

猜你喜欢

转载自www.cnblogs.com/superfeeling/p/12460496.html