3

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?

4

2 回答 2

10

那是因为您没有名为“record”的字段,您将其别名为“CUSTOMER_NO”,因此将代码更改为:

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

也就是说,您也可以使用 index 而不是 name 来阅读第二列:

lblWebMasterMessage.Text += "record " + reader[1] + "<br />";
于 2013-02-21T15:04:50.850 回答
2

在我的情况下,这个错误是因为我不小心在命令文本中执行了两个 select 语句。我有两个单独的输出结果,第一个输出不包含我正在阅读的列名,因此出现了错误。

于 2016-10-27T06:08:52.237 回答