1、datatable与datagrid之间的绑定

时间:2021-09-19 23:54:39

1.前台代码:

插入一个datagrid控件,设置几列。

这里有两点要注意:

1)为了显示所要查询的日期,我将前台的列名与后台查询出来的日期绑定了,用了x:Name这个属性

2)与后台datatable绑定的方法为  Binding="{Binding dt定义的列名}"

<DataGrid AutoGenerateColumns="False" Height="" HorizontalAlignment="Left" Margin="219,174,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding 单位}" x:Name="danwei" FontSize="" Header="" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
<DataGridTextColumn x:Name="first" FontSize="" Binding="{Binding first}" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
<DataGridTextColumn x:Name="second" FontSize="" Binding="{Binding second}" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
<DataGridTextColumn x:Name="third" FontSize="" Binding="{Binding third}" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
<DataGridTextColumn x:Name="fourth" FontSize="" Binding="{Binding fourth}" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
<DataGridTextColumn x:Name="fifth" FontSize="" Binding="{Binding fifth}" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
<DataGridTextColumn x:Name="sixth" FontSize="" Binding="{Binding sixth}" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
<DataGridTextColumn x:Name="seventh" FontSize="" Binding="{Binding seventh}" IsReadOnly="True" Width="0.1*" FontWeight="Normal"/>
</DataGrid.Columns>
</DataGrid>

2.后台代码

1)根据x:Name传递给前台列名,这样显示出来的就是自己定义的日期

            danwei.Header = "单位";
first.Header = datePicker1.SelectedDate.Value.AddDays(-).ToString();
second.Header = datePicker1.SelectedDate.Value.AddDays(-).ToString();
third.Header = datePicker1.SelectedDate.Value.AddDays(-).ToString();
fourth.Header = datePicker1.SelectedDate.Value.AddDays(-).ToString();
fifth.Header = datePicker1.SelectedDate.Value.AddDays(-).ToString();
sixth.Header = datePicker1.SelectedDate.Value.AddDays(-).ToString();
seventh.Header = datePicker1.SelectedDate.Value.AddDays(-).ToString();

2)绑定列的数据,即通过dt定义的列名,将获得的数据传值到前台

            DataTable dt = new DataTable();
dt.Columns.Add("单位", typeof(string));
dt.Columns.Add("first", typeof(double));
dt.Columns.Add("second", typeof(double));
dt.Columns.Add("third", typeof(double));
dt.Columns.Add("fourth", typeof(double));
dt.Columns.Add("fifth", typeof(double));
dt.Columns.Add("sixth", typeof(double));
dt.Columns.Add("seventh", typeof(double));

3)给dt传递查询出来的数据  dt.Rows.Add(......)    注意:括号中的列数应该与刚刚定义的列数保持一致。

4)绑定数据  dataGrid1.ItemsSource = dt.DefaultView;