繁体   English   中英

“索引超出数组范围” c#

[英]“Index was outside the bounds of the array” c#

我写了一个关于客户注册的程序。 我保存了客户信息。 到txt文件,我将客户部门保存在访问数据库中。 我想对借款人从小到大或从大到小进行排名。因此,我在债务列中传输了数据,并使用冒泡排序。 但是我收到了在标题中指定的错误。如何解决?

  private void button2_Click(object sender, EventArgs e)
    {
        listBox3.Items.Clear();
        OleDbCommand komut = new OleDbCommand();

       conn.Open();


        OleDbCommand cmd = new OleDbCommand(" SELECT  RemainingDept FROM Dept_Tbl  ", conn);

        OleDbDataReader dr = cmd.ExecuteReader();
        List<string> liste = new List<string>();
        List<string> liste1 = new List<string>();
        while ((dr.Read()))
        {

            liste.Add(dr["RemainingDept"].ToString());

        }


        int[] B;
        string[] A = liste.ToArray();

        B = Array.ConvertAll<string, int>(A, int.Parse);

        int tmp;
        for (int i = 0; i <A.Length ; i++)
        {
            for (int j=A.Length-1; j>i; j++)
            {
                if (B[j - 1] > B[j])
                {
                    tmp = B[j - 1];
                    B[j - 1] = B[j];
                    B[j] = tmp;
                listBox3.Items.Add(tmp.ToString());
                }
            }

        }

        conn.Close();
    }
} 

    } 

在此处输入图片说明

for循环中的错误,因为j将永远长大。 另外,最好将A.Length更改为B.Length ,尽管它们的大小相同,但是您是在B而不是A上操作,因此这使代码更易于理解。 这是带有示例的代码:

string[] A = new string[]{"60","120","10","40","80","20"};
int[] B = Array.ConvertAll<string, int>(A, int.Parse);

int temp;
for (int i = 0; i < B.Length ; i++)
{
    for (int j = B.Length - 1; j > i; j--)
    {
        if (B[j - 1] > B[j])
        {
            tmp = B[j - 1];
            B[j - 1] = B[j];
            B[j] = tmp;
        }
    }
}
// Results in 10,20,40,60,80,120 

编辑:如果要listBox3包含已排序的数组,则必须放在排序循环之后,如下所示:

listBox3.Items.Clear(); //Use this line if you need to clear the contents.
for(int i = 0; i < B.Length; i++)
{
    listBox3.Items.Add(B[i].ToString());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM