动态绑定数据网格 WPF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19750770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:00:17  来源:igfitidea点击:

Dynamically binding a datagrid WPF

wpfvb.netxamldatagrid

提问by RehmaNatiq

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?

如何解决这个问题呢?它如何将数据集动态绑定到数据网格?

回答by Rohit Vats

Bind ItemsSourcewith DataViewinstead of DataTable. You can get DataView with either of the approaches mentioned below -

绑定ItemsSourceDataView替代DataTable。您可以使用下面提到的任何一种方法获取 DataView -

DataGrid1.ItemsSource = ds.Tables("a").DefaultView;

OR use extension method AsDataView-

或使用扩展方法AsDataView-

DataGrid1.ItemsSource = ds.Tables("a").AsDataView();

回答by HichemSeeSharp

You are a bit mixing dynamic and static binding. you should remove ItemsSource="{Binding ds}"from XAML and DataGrid1.DataContext = ds.DefaultViewManagerfrom code behind as you're communicating with ItemsSource from code behind.

你有点混合动态和静态绑定。当您从代码背后的 ItemsSource 进行通信时,您应该ItemsSource="{Binding ds}"从 XAML 和 DataGrid1.DataContext = ds.DefaultViewManager背后的代码中删除。