从数据表中选择和更新数据

时间:2015-06-20 10:12:27

标签: c# asp.net datatable

我通过使用以下代码从我的数据表中选择数据,但它抛出了一个我不熟悉的异常。

  

“索引超出了数组的范围。”

tblRooms.Select(IDRoom = 4)这是在房间里IDRoom的价值,但我不知道它为什么会导致错误。

foreach (DataRow dr in tblRoomCart.Rows)
{

     DataRow drRoom = tblRooms.Select("IDRoom =" + dr["IDRoom"])[0];//here the error in this line 
}

1 个答案:

答案 0 :(得分:0)

正如异常所说,索引超出范围,您正在读取第一个元素(索引为0),但集合中没有元素。
它与此相同:

int[] array = new int[0];
int x = array[0];//You will get an exception here

添加if语句以确保至少有1个元素,例如:

int[] array = new int[0];
if (array.Length > 0)
{
        int x = array[0];
}
相关问题