Out of range error on SqlDataReader

为君一笑 提交于 2019-12-02 00:47:08

问题


I'm using a SqlDataReader and get this exception when trying to read a column...

System.IndexOutOfRangeException: record

Here is the code...

SqlCommand select = new SqlCommand("SELECT RTRIM(LTRIM(PART_NO)) AS PART_NO, record AS CUSTOMER_NO FROM [RMAData].[dbo].[IMPORTING_ORDER_EDI] WHERE sessionID = '" + Session.SessionID + "'", connection);
SqlDataReader reader = select.ExecuteReader();

if (reader.HasRows)
{
   while (reader.Read())
   {
       lblWebMasterMessage.Text += "record " + reader["record"].ToString() + "<br />";
...

If I change the lblWebMasterMessage.Text to the following it works just fine...

lblWebMasterMessage.Text += "record " + reader["PART_NO"].ToString() + "<br />";

The difference between record and PART_NO in the SQL Server table is that 'record' is a primary key and an int, PART_NO is a varchar(100).

The trouble is, I need the 'record' to identify the record to update it later...

I really can't see why it can return one field and not the other?


回答1:


That's because you have no field named "record", you aliased it to "CUSTOMER_NO" so change the code to:

lblWebMasterMessage.Text += "record " + reader["CUSTOMER_NO"].ToString() + "<br />";

That said, you can also use index instead of name so to read the second column:

lblWebMasterMessage.Text += "record " + reader[1] + "<br />";



回答2:


In my case this error was because I was accidentally executing two select statements in my command text. I had two separate output results and the first output didn't contain the column name I was reading and hence the error.



来源:https://stackoverflow.com/questions/15005479/out-of-range-error-on-sqldatareader

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