将datagrid绑定到datareader [英] Bind datagrid to datareader
问题描述
我希望能够在文本框中输入SQL并在WPF Datagrid中显示结果。我想从 SqlDataReader
开始,然后将datagrid的 ItemsSource
设置为数据读取器:
I want to be able to enter SQL into a textbox and display the results in a WPF Datagrid. I thought to start with an SqlDataReader
, and set the datagrid's ItemsSource
to the data reader:
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = sql.Text;
sqlResults.ItemsSource = cmd.ExecuteReader();
}
但这失败,并出现以下错误:无效尝试在读者关闭时调用FieldCount
,据我理解,这意味着WPF开始阅读行对象的 FieldCount
属性时, using
块已经退出。
but this fails with the following error: Invalid attempt to call FieldCount when reader is closed
, which I understand to mean that by the time WPF gets around to reading the FieldCount
property of the row object, the using
block has already been exited.
所以我尝试使用LINQ和 ToList
,以获得保留在内存中的内容:
So I tried using LINQ and ToList
, to get something that would persist in memory:
sqlResults.ItemsSource = cmd.ExecuteReader().Cast<DbDataRecord>().ToList();
但这仅显示每一行的 FieldCount,这显然是唯一 DbDataRecord
有。
but this only displays the 'FieldCount' for each row, which is apparently the only property which DbDataRecord
has.
我考虑过的一些解决方案:
Some solutions I have considered:
- 绑定到DataTable而不是DataReader?但是我不需要编辑功能。
- 是否将每一行选择到内存数据结构中?我可以使用什么数据结构?我不能使用匿名类型,因为列的名称和类型根据SQL语句而变化。如果我使用
List< object>
,数据网格将如何知道为列表中的每个对象生成列? - 创建自定义类型描述符?
- Bind to a DataTable instead of a DataReader? But I don't need editing capabilities.
- Select each row into an in-memory data structure? What data structure could I use? I can't use anonymous types, because the names and types of the columns change based on the SQL statement. If I use
List<object>
, how will the datagrid know to generate columns for each object in the list? - Create a custom type descriptor? It seems like overkill.
但是我觉得解决方案应该非常简单容易。我在这里错过了一些基本的东西吗?
But I feel the solution should be very simple and easy. Am I missing something basic here?
推荐答案
也许DataTable是过分的,但是它可以满足您的需要。
Maybe a DataTable is overkill but it does what you need it to do.
这篇关于将datagrid绑定到datareader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!