wsdfg

wsdfg

  • NA
  • 27
  • 0

ArgumentOutOfRangeException was unhandled

Mar 3 2010 4:01 PM
I wrote a program that would display the information of a car when you input the cardnum. made it so that when you input another cardnum it will show the data for that car in another row on the datagridview. now I also made it that when you input a cardnum for a car thats already displayed it will remove it from the datagridview.. heres the problem, the program works fine until it removes a row. the next time I input the cardnum I get the error "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

heres the code

private void CheckKeys3(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
string card = textBox1.Text.ToString();
int cardnum = int.Parse(card);
park = park - 1;
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=car.mdb");
con.Open();

OleDbCommand queryString = new OleDbCommand("SELECT cardnum, ownerf, ownerl, make, model, year, color, chassisnumber, platenumber, controlnumber FROM vehicle WHERE vehicle.cardnum = " + cardnum + "",con);
OleDbDataReader dr = queryString.ExecuteReader();
if (dr.Read())
{
DataGridViewRow row = new DataGridViewRow();
this.dataGridView1.Rows.Add(row);
dataGridView1.Rows[i].Cells[0].Value = dr["cardnum"].ToString(); <----the error points here
dataGridView1.Rows[i].Cells[1].Value = dr["ownerf"].ToString();
dataGridView1.Rows[i].Cells[2].Value = dr["ownerl"].ToString();
dataGridView1.Rows[i].Cells[3].Value = dr["make"].ToString();
dataGridView1.Rows[i].Cells[4].Value = dr["model"].ToString();
dataGridView1.Rows[i].Cells[5].Value = dr["year"].ToString();
dataGridView1.Rows[i].Cells[6].Value = dr["color"].ToString();
dataGridView1.Rows[i].Cells[7].Value = dr["chassisnumber"].ToString();
dataGridView1.Rows[i].Cells[8].Value = dr["platenumber"].ToString();
dataGridView1.Rows[i].Cells[9].Value = dr["controlnumber"].ToString();

//this is where I remove the row
int k=i;

do
{
k = k - 1;

if (k >= 0)
{
string wah = dataGridView1[0, k].Value.ToString();
int weh = int.Parse(wah);
if (cardnum == weh)
{
dataGridView1.Rows.RemoveAt(k);
i = i - 1;
dataGridView1.Rows.RemoveAt(i);
i++;
}
}
} while (k >=0);


i++;
}
con.Close();
}

does anybody know how to fix it? or whats wrong?

Answers (9)