there is no row at position 1

2019-08-28 21:59发布

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++;

            }
}

2条回答
神经病院院长
2楼-- · 2019-08-28 22:29

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-08-28 22:49

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]

查看更多
登录 后发表回答