IndexOutOfRangeException未被用户代码处理

时间:2013-07-14 06:26:43

标签: c# asp.net sql linq

我的数据库设计是这样的:

列名:名称,数据类型:varchar(50)

当我将数据输入到visual studio中时,它会出现异常

IndexOutOfRangeException未被用户代码处理:索引超出了数组的范围。

using (var reader = command.ExecuteReader())
                        return reader.Cast<System.Data.IDataRecord>()
                            .Select(x => new JobInfo()
                            {

                                Name = x.GetString(0),


                            }).ToList();

2 个答案:

答案 0 :(得分:3)

x.GetString(0)可能是你的问题。数组在C#中基于0。如果该项没有元素,则尝试获取“0”(第一个)将导致抛出异常。这与尝试在8个元素阵列中获得第9个元素是一回事。

答案 1 :(得分:0)

当没有记录时,您正在尝试检索记录。检查您的datareader是否首先包含数据:

if (reader.HasRows)
{
  //get the record here
}