i write a program about customer registiriation. i saved customer inf. to txt file and i saved depts of customers in the access database. I want to rank the borrowers from small to large or large to small.So, i transfered of data in the debt column and use with bubble sort. but I'm getting the error I specified in the title.how to fix it?
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();
}
}
}
Your error in the for loop, as j
will grow up forever. Also, it may be good to change A.Length
to B.Length
, although they have the same size, you're operating on B not A, so this make the code more understandable. Here is the code with an example:
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
Edit: If you want listBox3
to contain the sorted array, you must put after the sorting loop, like this :
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.