Val K
Val K

Reputation: 331

SqlDataReader out of range exception.. cannot solve it

enter image description here

I have been trying to get it working for almost an hour now and cannot make any sense why it is not working. Please help!! This is my code

SqlDataReader rs = cmdGet.ExecuteReader();
rs.Read();
var id = Convert.ToInt32(rs["id"]);
var mt = rs["mt"].ToString();

The SQL statement is this:

  SELECT TOP 1 
      id = 0,
      mt = MT
  FROM 
      MyTable
  ORDER BY 
      2

I id = 0 and the code breaks at mt line. Throws:

System.IndexOutOfRangeException

What's wrong? I looked at a lot of posts but could not resolve it.

Upvotes: 1

Views: 129

Answers (1)

Saif
Saif

Reputation: 2679

the exception said that you have no field named mt so you need to change your query into this and it should work:

SELECT TOP 1 id, mt
FROM MyTable
 WHERE id = 0
ORDER BY 2

Upvotes: 1

Related Questions