C#for循环。索引超出范围

时间:2018-11-14 11:09:57

标签: c#

我遇到以下错误:

  

索引超出了数组的范围

for循环代码:

for (int i = 0; i < listEquipment.Items.Count - 1; i++)
{
   SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[EquipmentItems] ([RequestID], [TypeID]) VALUES (@RequestID, @TypeID)", conn);
   cmd.Parameters.Add("@RequestID", SqlDbType.Int).Value = userRequest;
   cmd.Parameters.Add("@TypeID", SqlDbType.Int).Value = (listEquipment.SelectedItems[i] as Equipment).equipmentID;
   cmd.ExecuteNonQuery();
}

出现错误的行:

cmd.Parameters.Add("@TypeID", SqlDbType.Int).Value = (listEquipment.SelectedItems[i] as Equipment).equipmentID;

请帮助!我是编程新手。

3 个答案:

答案 0 :(得分:5)

您循环所有项目,然后在$SCRIPT_VAR中访问该索引。但是可能没有选择所有项目,这意味着此集合较小,您无法访问它。

所以我假设您不想只循环选中的所有项目,所以请使用:

listEquipment.SelectedItems[i]

答案 1 :(得分:1)

更改

for (int i = 0; i < listEquipment.Items.Count - 1; i++)

 for (int i = 0; i < listEquipment.SelectedItems.Count; i++)

答案 2 :(得分:0)

您正在寻找类似的东西(让我通过以下代码中的注释失效):

  //DONE: make sql readable 
  string sql = 
    @"INSERT INTO [dbo].[EquipmentItems] (
        [RequestID], 
        [TypeID]) 
      VALUES (
        @RequestID, 
        @TypeID)";

  // Create command once - use many (within the loop)
  //DONE: wrap IDisposable into using  
  using (SqlCommand cmd = new SqlCommand(sql, conn)) {
    // user request is the same for all the equipment
    cmd.Parameters.Add("@RequestID", SqlDbType.Int).Value = userRequest;
    cmd.Parameters.Add("@TypeID", SqlDbType.Int);

    //DONE: foreach + OfType<> is by far more readable in the context: 
    //     "for each selected equipment execute a query"
    foreach (Equipment equipment in listEquipment.SelectedItems.OfType<Equipment>()) {
      cmd.Parameters["@TypeID"].Value = equipment.equipmentID;

      cmd.ExecuteNonQuery();
    } 
  }