超出数组边界的索引c#

时间:2015-03-06 06:31:53

标签: c# arrays visual-studio-2010 web-services windows-forms-designer

我确实收到了这个错误...请帮帮我们 这是我的代码

private int getLastRowCount()
{
    return dg.Rows.Count - 1;
}
double[] minAmounts = new double[getLastRowCount()];
double[] maxAmounts = new double[getLastRowCount()];
double[] chrgeValues = new double[getLastRowCount()];
   for (int ctr = 0; (ctr <= getLastRowCount()); ctr++)
   {
        minAmounts[ctr] = Convert.ToDouble(dg[0, ctr].Value);
        maxAmounts[ctr] = Convert.ToDouble(dg[1, ctr].Value);
        chrgeValues[ctr] = Convert.ToDouble(dg[2, ctr].Value);
   }

3 个答案:

答案 0 :(得分:0)

C#中的数组是基于零的,因此循环到&lt; =到getLastRowCount()会使你超过结尾。您还将行数缩短了1(在getLastRowCount()中)。你的代码应该是:

private int getLastRowCount()
{
    return dg.Rows.Count;
}

double[] minAmounts = new double[getLastRowCount()];
double[] maxAmounts = new double[getLastRowCount()];
double[] chrgeValues = new double[getLastRowCount()];

for (int ctr = 0; (ctr < getLastRowCount()); ctr++)
{
    //minAmounts[ctr] = Convert.ToDouble(dg[0, ctr].Value);
    //maxAmounts[ctr] = Convert.ToDouble(dg[1, ctr].Value);
    //chrgeValues[ctr] = Convert.ToDouble(dg[2, ctr].Value);

    // it should be [row, col]. This assumes you have at least 3 columns.
    minAmounts[ctr] = Convert.ToDouble(dg[ctr, 0].Value);
    maxAmounts[ctr] = Convert.ToDouble(dg[ctr, 1].Value);
    chrgeValues[ctr] = Convert.ToDouble(dg[ctr, 2].Value);
}

虽然您可能还应该将getLastRowCount()的值存储在某处而不是继续调用它。

答案 1 :(得分:0)

所有三个数组必须具有与dg中行数相同的容量(假设它是数据网格)。

对于ctr计数器,rows.Count - 1很好,但是为了定义数组的容量,这会使容量减少1。

答案 2 :(得分:0)

按照评论:

private int getLastRowCount()
{
    return dg.Rows.Count - 1; // let's assume this will return 5.
}
// here we declaring 3 arrays of the size 5.
double[] minAmounts = new double[getLastRowCount()];
double[] maxAmounts = new double[getLastRowCount()];
double[] chrgeValues = new double[getLastRowCount()];
// this loop will iterate 6 times: 0,1,2,3,4,5 since getLastRowRount() result to 5.
   for (int ctr = 0; (ctr <= getLastRowCount()); ctr++)
   {
        minAmounts[ctr] = Convert.ToDouble(dg[0, ctr].Value);
        maxAmounts[ctr] = Convert.ToDouble(dg[1, ctr].Value);
        chrgeValues[ctr] = Convert.ToDouble(dg[2, ctr].Value);
   }

因此,解决方案如Ceisc所述,更改此行

for (int ctr = 0; (ctr <= getLastRowCount()); ctr++)

是:

for (int ctr = 0; (ctr < getLastRowCount()); ctr++)