datagridview中的空行未插入数据库

时间:2017-11-02 07:15:44

标签: c# datagridview null

我有一个Datagridview,其中我添加了一些列,我想在运行表单时向其添加数据。问题是在一行之后自动添加一个空行然后它显示一个错误,那么我该怎么做才能避免空行。我的代码是

    foreach (DataGridViewRow row in dataGridView1.Rows)
      {        
        string batchid =row.Cells["batchid"].Value.ToString();
        string unitid = row.Cells["unitid"].Value.ToString();
        string unitmf = row.Cells["unitmf"].Value.ToString();
        string barcode = row.Cells["barcode"].Value.ToString();
        string expmonth = row.Cells["expmonth"].Value.ToString();
        string expyear = row.Cells["expyear"].Value.ToString();
        string expdays = row.Cells["expdays"].Value.ToString();
        string purchaserate=row.Cells["purchaserate"].Value.ToString();            
        string openingstock = row.Cells["openingstock"].Value.ToString();
        string rate1 = row.Cells["rate1"].Value.ToString();
        string rate2 = row.Cells["rate2"].Value.ToString();
        string rate3 = row.Cells["rate3"].Value.ToString();
        string rate4 = row.Cells["rate4"].Value.ToString();
        string dc ="INSERT INTO itemstock(main_id, comp_id, firm_id,  trans_id, user_id, computer_id,item_id, batch_id, bar_code, unit_id, unit_mf,  salesrate1, salesrate2, salesrate3, salesrate4, exp_days, exp_month, exp_year, purch_rate, current_stock, costbase, lastcost, opening_cost, opening_stock)VALUES(1,1,1,1,1,1,'" + itemid + "','" + batchid + "','"+barcode+ "','" + unitid + "','" + unitmf + "','" + rate1 + "','" + rate2 + "','" + rate3 + "','" + rate4 + "','" + expdays + "','" + expmonth + "','" + expyear + "','" + purchaserate + "','" + openingstock + "','" + txtcurrentcost.Text + "','" + txtlastcost.Text + "','" + txtopeningcost.Text + "','" + openingstock + "',)";
      }

1 个答案:

答案 0 :(得分:0)

在DataGridView的底部有一个空行......你必须跳过循环中的那一行......就像这样:

foreach (DataGridViewRow row in dataGridView1.Rows)
{  
    if (row.IsNewRow) continue;
    ...