there is no row at position 1

2019-08-28 22:18发布

问题:

i'm creating a window form and i run this code ,firsttime i was add avalue in datagirdview correctly but the secondtime i'm trying to add a value in datagirdview but getting this error

There is no row at position 1. this line

        double b = Convert.ToDouble(dt.Rows[count][1]);

        int count = 0;

        private void button1_Click(object sender, EventArgs e)
        {
            id = Convert.ToInt32(txt_item.Text);

            date = DateTime.Now;

        string q = "select pro_name , amount from Product where pro_id =  " + id ;
        dt = g.selectQuery(q);            

        if (dt.Rows.Count > 0)
        {
            if (!dt.Columns.Contains("Quantity selected"))
            {
                dt.Columns.Add("Qty");
            }
            if (!dt.Columns.Contains("Total"))
            {
                dt.Columns.Add("Total");
            }               
            double b = Convert.ToDouble(dt.Rows[count][1]);
            dt.Rows[count][2] = 1;
            dt.Rows[count][3] =  1*b;                
            dataGridView1.DataSource = dt;
            count++;

            }
}

回答1:

You should write it like this:

dt.Rows[dt.Rows.Count-1][1]

The problem is that the count is global and if you click the button twice the value of count will be 1. In this case if the Rows.Count is 1, you are going to have only row[0] in your DataTable.

Becausee of that write it like: dt.Rows[dt.Rows.Count-1][1] or dt.Rows[0][1]



回答2:

You have a global variable count; It starts at zero and you increment it to one.

If your query returns just one row the second time you run it, the row will be at index 0, not 1.