[英]Dynamically binding a datagrid WPF
I'm binding data to a datagrid dynamically but it does not shows the data. 我正在动态地将数据绑定到数据网格,但它不显示数据。 It gives me this five columns in it: RowError, RowState, table, ItemArray and HasError. 它给了我这五列:RowError,RowState,table,ItemArray和HasError。
But the row count is correct it gives same row count as I have in database. 但是行数是正确的,它给出了与我在数据库中相同的行数。
This is the Vb code: 这是Vb代码:
Dim con As New OdbcConnection("dsn=PAUSPAN")
con.Open()
Dim cmd As New OdbcCommand("select * from tbl_chart", con)
Dim da As New OdbcDataAdapter(cmd)
'Dim dt As New DataTable("a")
Dim ds As New DataSet()
ds.Tables.Add("a")
da.Fill(ds, "a")
MsgBox(ds.Tables("a").Rows.Count.ToString)
DataGrid1.ItemsSource = ds.Tables("a").AsEnumerable.ToList()
'DataGrid1.DataContext = ds.DefaultViewManager
con.Close()
And this is the XAML code: 这是XAML代码:
<Window x:Class="datagrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="datagrid" Height="344" Width="599">
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="486,225,0,0" Name="Button1"
VerticalAlignment="Top" Width="75" />
<DataGrid Height="241" HorizontalAlignment="Left"
Margin="12,12,0,0"
Name="DataGrid1" VerticalAlignment="Top"
Width="386" ItemsSource="{Binding ds}" />
</Grid>
</Window>
how to solve this problem? 如何解决这个问题呢? how do it bind the dataset to datagrid dynamically? 它如何动态地将数据集绑定到数据网格?
Bind ItemsSource
with DataView
instead of DataTable
. 使用DataView
而不是DataTable
绑定ItemsSource
。 You can get DataView with either of the approaches mentioned below - 您可以使用以下任一方法获取DataView -
DataGrid1.ItemsSource = ds.Tables("a").DefaultView;
OR use extension method AsDataView
- 或使用扩展方法AsDataView
-
DataGrid1.ItemsSource = ds.Tables("a").AsDataView();
You are a bit mixing dynamic and static binding. 你有点混合动态和静态绑定。 you should remove ItemsSource="{Binding ds}"
from XAML and DataGrid1.DataContext = ds.DefaultViewManager
from code behind as you're communicating with ItemsSource from code behind. 当你从后面的代码与ItemsSource进行通信时,你DataGrid1.DataContext = ds.DefaultViewManager
从代码中删除XAML和DataGrid1.DataContext = ds.DefaultViewManager
中的ItemsSource="{Binding ds}"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.