title: C# SqlCommand - Setting resultset to a variable
body: <p>I'm running a SQL command in C# that returns one value (a String).  I'm then trying to save it to a variable, but it always throws this exception:</p>
  
  <blockquote>
    <p>A first chance exception of type 'System.InvalidOperationException' occurred in System.Data.dll
        The thread '' (0x1bbc) has exited with code 0 (0x0).
        System.InvalidOperationException: Invalid attempt to read when no data is present.
           at System.Data.SqlClient.SqlDataReader.GetValue(Int32 i)</p>
  </blockquote>
  
  <p>However, when I run the same command in SQL Server, it definitely outputs a value.</p>
  
  <pre><code>myCommand = new SqlCommand("SELECT TrialName FROM dbo.CT WHERE NumId='"+TrialId+"'", myConnection);    
  SqlDataReader dr = myCommand.ExecuteReader();  
  String TName = dr[0].ToString(); 
  </code></pre>
  
  <p>Even if I hardcode the whole sqlcommand (instead of using the TrialId variable) it still throws the exception.  What is going on here?</p>