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

时间:2018-01-04 09:23:13

标签: c# ms-access bubble-sort

我写了一个关于客户注册的程序。我救了客户inf。到txt文件,我在访问数据库中保存了客户的depts。 我想将借款人从小到大或从大到小排名。所以,我在债务栏中转移数据并使用冒泡排序。但是我得到了我在title.how中指定的错误来解决它?

  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();
    }
} 

    } 

enter image description here

1 个答案:

答案 0 :(得分:0)

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());
}