【问题标题】:Unhandled Exception when Filling a datagrid View填充 datagridView 时出现未处理的异常
【发布时间】:2016-11-21 13:44:17
【问题描述】:

我正在开发一个 C# winform 应用程序。我的目标是在用户从 datetimePicker 中选择一个日期后,执行查询并返回仅包含相同记录的结果。接下来,用户将选择这些记录之一,该记录应使用组合框(custlocation)中与该客户关联的所有订购商品填充网格。这部分正在工作。问题是,现在我一直试图让我的 dataGridView1 填充。我不断得到:

在 mscorlib.dll 中发生“System.ArgumentOutOfRangeException”类型的未处理异常

附加信息:索引超出范围。必须是非负数且小于集合的大小。

我检查了我的查询,它返回了正确的结果。

private void custlocation_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlDataAdapter da = new SqlDataAdapter(
        "Select [orderitem].*, [orderitem].qty, [orderitem].descrip, [orderitem].tally "+
        "from [orderitem] inner join [Order] on [orderitem].orderId = [order].ct "+
        "where [order].loadDate='" + dateTimePicker1.Value.Date + "' "+
        "and [order].addr1=" + custlocation.Text, conn);

    DataTable lt = new DataTable();
    //da.Fill(lt);

    //dataGridView1.DataSource = lt;
    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = lt;
    dataGridView1.Columns[4].Name = "loadtickets";
    dataGridView1.Rows[a].Cells[0].Value = rdr["orderID"].ToString();
    dataGridView1.Rows[a].Cells[1].Value = rdr["qty"].ToString();
    dataGridView1.Rows[a].Cells[2].Value = rdr["descrip"].ToString();
    dataGridView1.Rows[a].Cells[3].Value = rdr["tally"].ToString();
}

【问题讨论】:

  • 哪一行抛出异常?您在那里使用了很多数组索引器,其中一个似乎不正确(或假设状态不正确)。当你调试这个时,当抛出异常时,你试图访问什么索引,为什么你认为它应该存在?
  • 我在第 5 行获得豁免。这应该会拉出多个行项目来填充网格。
  • 哪一行是“第 5 行”? (提示:在发布的代码示例中,第 5 行已被注释掉。)此外,当您调试它时,请检查您正在使用的对象的实际运行时值。您正在尝试访问一个不存在的值。
  • 尝试在调试模式下单步执行,但我注意到您似乎正在使用数据读取器插入循环 (rdr) 中的代码,该代码未在发布的代码块中的任何位置定义。
  • a 很可能超出行的范围,或者一行中没有 4 个单元格。

标签: c# winforms datagridview


【解决方案1】:

数组是从零开始的,就像您在 Cells 属性上使用的一样。似乎您正在尝试更改第 5 列的名称,但您只有 4 个。

改变

dataGridView1.Columns[4].Name = "loadtickets";

dataGridView1.Columns[3].Name = "loadtickets";

【讨论】:

  • 我现在无法绑定多部分标识符“System.Data.DataRowView”。
  • 检查this
【解决方案2】:

在 mscorlib.dll 中发生“System.ArgumentOutOfRangeException”类型的未处理异常

附加信息:索引超出范围。必须为非负数且小于集合的大小。

这个错误是因为你必须像@Anderson Pimentel说的那样使用dataGridView1.Columns[3].Name = "loadtickets";

无法绑定多部分标识符“System.Data.DataRowView”

这个错误是由于查询造成的。

 SqlDataAdapter da = new SqlDataAdapter(
    "Select [orderitem].*, [orderitem].qty, [orderitem].descrip, [orderitem].tally "+
    "from [orderitem]  inner join [Order] on [orderitem].orderId = [order].ct "+
    "where [order].loadDate='" + dateTimePicker1.Value.Date + "' "+
    "and [order].addr1=" + custlocation.Text, conn);

您选择了orderitm.*orderitem 中的所有列)和同一张表中的 3 列 ([orderitem].qty, [orderitem].descrip, [orderitem].tally)。所以这些列是重复的

您必须删除这些重复项或为它们指定别名,例如 [orderitem].qty AS Quantity

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    相关资源
    最近更新 更多