0

I need to operate the data added to the Datagridview from sql database but I am receiving an argument out of range exception "Index was out of range. Must be non-negative and less than the size of the collection." here is my code. the SQL data is simply integers from 1-10

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=HAIER-PC;Initial Catalog=pdcs;Integrated Security=True;");
    con.Open();
    SqlCommand cnd = new SqlCommand("SELECT * from CDes where Age='" + comboBox1.Text + "' AND Exper='" + comboBox2.Text + "'AND Design='" + comboBox3.Text + "'  ", con);
    SqlDataReader rdr = cnd.ExecuteReader();
    while (rdr.Read())

    {
        int n = dataGridView1.Rows.Add();
        dataGridView1.Rows[n].Cells[0].Value = rdr["C_ID"].ToString();
        dataGridView1.Rows[n].Cells[1].Value = rdr["Age"].ToString();
        dataGridView1.Rows[n].Cells[2].Value = rdr["Exper"].ToString();
        dataGridView1.Rows[n].Cells[3].Value = rdr["Design"].ToString();
        dataGridView1.Rows[n].Cells[4].Value = rdr["Shell"].ToString();
        dataGridView1.Rows[n].Cells[5].Value = rdr["Base"].ToString();
        dataGridView1.Rows[n].Cells[6].Value = rdr["Vnt"].ToString();
        dataGridView1.Rows[n].Cells[7].Value = rdr["Price"].ToString();
        dataGridView1.Rows[n].Cells[8].Value = rdr["Impactliner"].ToString();
        dataGridView1.Rows[n].Cells[9].Value = rdr["Eyeport"].ToString();
        dataGridView1.Rows[n].Cells[10].Value = rdr["Face"].ToString();
        dataGridView1.Rows[n].Cells[11].Value = rdr["Comfort"].ToString();
        dataGridView1.Rows[n].Cells[12].Value = rdr["Strap"].ToString();
        dataGridView1.Rows[n].Cells[13].Value = rdr["Wgt"].ToString();
    }
    rdr.Close();
    con.Close();

}

private void button2_Click(object sender, EventArgs e)
{
    double w1=2.67;
    for (int i = 0; i <= dataGridView1.Rows.Count; i++)
    {
        double shell = Convert.ToDouble(dataGridView1.Rows[i].Cells[5].Value); //here is the exception
        double s1 =  shell -  w1;
        textBox1.Text = s1.ToString();
    }
}

Data is already added to the datagridview

Kamal
  • 2,512
  • 2
  • 34
  • 48
  • The exception has a **stack trace** that tells you **where** it was raised. You can set a break-point around that code and **debug** your code. A hint: I guess `i <= dataGridView1.Rows.Count` is obviously wrong. Arrays are indexed 0-based, so the last valid index is `Count-1`, not `Count`. So it should read `i < dataGridView1.Rows.Count` – René Vogt Aug 23 '19 at 10:59
  • And note that you only used the value of the last row. The previous texts are overwritten by the last `textBox1.Text = s1.ToString();`. – René Vogt Aug 23 '19 at 11:02
  • Thanks your suggestion helped and I have to overwrite the values in my complete code – annam jamshed Aug 23 '19 at 11:07

0 Answers0