Stuart Stuart - 11 months ago 72
ASP.NET (C#) Question

Out of range error on SqlDataReader

I'm using a

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
to the following it works just fine...

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

The difference between record and
in the SQL Server table is that 'record' is a primary key and an
is a

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?

Answer Source

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 />";