0

Why is data read from SqlDataReader not available to a method call? I have a table, with 'id' as column in it. When I make a query to database, it returns rows.

This code doesnt work (Says 'id' column doesnt exist):

con.Open();
SqlDataReader requestReader = cmd.ExecuteReader();
if (requestReader.HasRows)
{
   DataTable requestTable = requestReader.GetSchemaTable();
   request = ReadRequest(requestTable.Rows[0]);        
}

con.Close();

while this one works:

con.Open();
SqlDataReader requestReader = cmd.ExecuteReader();
if (requestReader.HasRows)
{
   DataTable requestTable = requestReader.GetSchemaTable();
   var requestRow = requestTable.Rows[0];
   request = new Request();
   request.UniqueId = (string)requestRow["id"];
}

con.Close();
2
  • And what is the code of that ReadRequest that doesn't work? Commented Apr 7, 2014 at 10:15
  • 1
    stupid question. Like Tim said, even the second approach didnt work, but due to quick testing and code-structuring, I didnt catch that. Thanks all. Commented Apr 7, 2014 at 11:00

1 Answer 1

1

You are using DataReader.GetSchemaTable which returns a DataTable with all schema informations for a given table.

It has following columns:

ColumnName
ColumnOrdinal
ColumnSize
NumericPrecision
// .. 26 others

So you don't find your id-column which belongs to your table. That's why you get the error "'id' column doesnt exist". I doubt that your second approach works. I don't see why you need GetSchemaTable at all. You just have to advance the reader to the next record:

if (requestReader.HasRows && requestReader.Read())
{
   int id = requestReader.GetInt32(requestReader.GetOrdinal("id"));
   // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.