3

I want to save the data from datagrid to database, I used the following code.

 foreach (DataGridViewRow r in dataGridView_displaycount.Rows)
        {
            SqlCommand cmd = new SqlCommand("insert into StocktransferlocationDetails(date,stocktransferlocation,Itemcode,Count,Description) values(@date,@stocktransferlocation,@Itemcode,@Count,@Description) ", con);

            cmd.Parameters.AddWithValue("@date",System.DateTime.Now);
            cmd.Parameters.AddWithValue("@stocktransferlocation", comboBox_locationfrom.SelectedText+"-"+comboBox_locationto.SelectedText);
            cmd.Parameters.AddWithValue("@Itemcode", r.Cells[1].Value.ToString());
            cmd.Parameters.AddWithValue("@Count", r.Cells[2].Value.ToString());
            cmd.Parameters.AddWithValue("@Description", r.Cells[3].Value.ToString());
            cmd.ExecuteNonQuery();
        }

Here my problem is the datagrid contains the empty row at the last. So I write the data and when it comes to the empty row it throws me an error.

4

4 回答 4

2

为什么在这里使用foreach循环?

使用for循环,例如:

for(int i=0; i<dataGridView_displaycount.Rows.Count-1; i++)
{
   //Your code
}

这应该是解决您的问题而不是任何其他代码更改的简单解决方案。

更新:将 gridview 数据添加到数据库:

for(int i=0; i< dataGridView_displaycount.Rows.Count-1;i++)
 {
    Strquery= @"Insert into StocktransferlocationDetails(date,stocktransferlocation,....) values (" 
                + System.DateTime.Now +", "+ comboBox_locationfrom.SelectedText+"-"+comboBox_locationto.SelectedText +"," 
                + dataGridView_displaycount.Rows[i].Cells[1].Value +".......);";
    cmd.CommandText = Strquery;
    cmd.ExecuteNonQuery();
 }
于 2012-10-08T07:05:39.167 回答
0

你可以试试这个最后一行:

cmd.Parameters.AddWithValue("@Description", r.Cells[3].Value ?? DBNull.Value); 
于 2012-10-08T07:07:43.143 回答
0

尝试检查空值,如下面的代码所示:

foreach (DataGridViewRow r in dataGridView_displaycount.Rows)
{
    SqlCommand cmd = new SqlCommand("insert into StocktransferlocationDetails(date,stocktransferlocation,Itemcode,Count,Description) values(@date,@stocktransferlocation,@Itemcode,@Count,@Description) ", con);

    cmd.Parameters.AddWithValue("@date", System.DateTime.Now);
    cmd.Parameters.AddWithValue("@stocktransferlocation", comboBox_locationfrom.SelectedText + "-" + comboBox_locationto.SelectedText);

    if (r.Cells[1] != null && r.Cells[1].Value != null)
        cmd.Parameters.AddWithValue("@Itemcode", r.Cells[1].Value.ToString());
    if (r.Cells[2] != null && r.Cells[2].Value != null)
        cmd.Parameters.AddWithValue("@Count", r.Cells[2].Value.ToString());
    if (r.Cells[3] != null && r.Cells[3].Value != null)
        cmd.Parameters.AddWithValue("@Description", r.Cells[3].Value.ToString());

    cmd.ExecuteNonQuery();
}
于 2012-10-08T07:05:14.563 回答
0

You Can Use for Like This :

For(int row=0;row<datagridview.rows.count;row++)

{
//Do Work
}
于 2012-10-08T06:51:21.803 回答