Bind datagrid to datareader

陌路散爱 提交于 2019-12-20 03:16:54

问题


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();
}

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.

So I tried using LINQ and ToList, to get something that would persist in memory:

sqlResults.ItemsSource = cmd.ExecuteReader().Cast<DbDataRecord>().ToList();

but this only displays the 'FieldCount' for each row, which is apparently the only property which DbDataRecord has.

Some solutions I have considered:

  • 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?


回答1:


Maybe a DataTable is overkill but it does what you need it to do.




回答2:


Well, yep, from what you've said, I would probably go with a struct containing properties that match the DB columns, and just fill that with the linq, so you can easily bind to it.

Working more with JavaScript, and wondering if you can find an equivalent to the Eval (which is suggested never to be used by the creator, btw :), and if that would help ...



来源:https://stackoverflow.com/questions/20530858/bind-datagrid-to-datareader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!