C# 在 WPF 中将 DataSet 绑定到 DataGrid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16964093/
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-08-10 08:15:10  来源:igfitidea点击:

Binding DataSet to DataGrid in WPF

c#wpf

提问by Tanuj Wadhwa

I know this has been asked before several times but I am not able to get this. I have a DataSetand a DataGrid. All I want to do is display the contents of the DataSetin the DataGrid.

我知道这已经被问过几次了,但我无法得到这个。我有一个DataSet和一个DataGrid。我想要做的就是DataSetDataGrid.

I have written this code :

我写了这段代码:

vConn = new OleDbConnection(ConnectionString);
vConn.Open();

vQuery = "Select * from Book";

DataSet vDs = new DataSet();
OleDbDataAdapter vAdap = new OleDbDataAdapter(vQuery, vConn);
vAdap.Fill(vDs,"Book");

GridData.DataContext = vDs.Tables["Book"];
vConn.Close();

But for some reason the data is not shown on DataGrid. I have tried setting AutoGenerateColumn to True/False. I also tried binding in xaml but it didn't work.

但由于某种原因,数据未显示在 DataGrid 上。我尝试将 AutoGenerateColumn 设置为 True/False。我也尝试在 xaml 中进行绑定,但没有奏效。

采纳答案by dkozl

this should work:

这应该有效:

GridData.ItemsSource = vDs.Tables["Book"].DefaultView;

or you can create your own DataView:

或者您可以创建自己的DataView

GridData.ItemsSource = new DataView(vDs.Tables["Book"]);

DataTable.DefaultViewgives you DataViewwhich implements IEnumerableand can be used as ItemsSource

DataTable.DefaultView为您提供DataView哪些工具IEnumerable并可用作ItemsSource

回答by Colin

OK, so heremay be the same issue you are dealing with.

好的,所以可能与您正在处理的问题相同。

You can try to set the ItemsSourceproperty as follow:

您可以尝试如下设置该ItemsSource属性:

GridData.ItemsSource = vDs.Tables["Book"].AsEnumerable();