title: Bind datagrid to datareader
body: <p>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 <code>SqlDataReader</code>, and set the datagrid's <code>ItemsSource</code> to the data reader:</p>
  
  <pre><code>using (var cmd = conn.CreateCommand()) {
      cmd.CommandText = sql.Text;
      sqlResults.ItemsSource = cmd.ExecuteReader();
  }
  </code></pre>
  
  <p>but this fails with the following error: <code>Invalid attempt to call FieldCount when reader is closed</code>, which I understand to mean that by the time WPF gets around to reading the <code>FieldCount</code> property of the row object, the <code>using</code> block has already been exited.</p>
  
  <p>So I tried using LINQ and <code>ToList</code>, to get something that would persist in memory:</p>
  
  <pre><code>sqlResults.ItemsSource = cmd.ExecuteReader().Cast&lt;DbDataRecord&gt;().ToList();
  </code></pre>
  
  <p>but this only displays the 'FieldCount' for each row, which is apparently the only property which <code>DbDataRecord</code> has.</p>
  
  <p>Some solutions I have considered:</p>
  
  <ul>
  <li>Bind to a DataTable instead of a DataReader? But I don't need editing capabilities.</li>
  <li>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 <code>List&lt;object&gt;</code>, how will the datagrid know to generate columns for each object in the list?</li>
  <li>Create a custom type descriptor? It seems like overkill.</li>
  </ul>
  
  <p>But I feel the solution should be very simple and easy. Am I missing something basic here?</p>