try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = @"Data Source=ZEE-PC\SQLEXPRESS;Initial Catalog=MyBill;Integrated Security=True;Pooling=False";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO stock VALUES(@productname, @packing,@totalquantity,@rate,@expry,@dealername)", con))
{
cmd.Parameters.AddWithValue("@productname", row.Cells["pname"].Value);
cmd.Parameters.AddWithValue("@packing", row.Cells["packing"].Value);
cmd.Parameters.AddWithValue("@totalquantity", row.Cells["quantity"].Value);
cmd.Parameters.AddWithValue("@rate", row.Cells["rate"].Value);
cmd.Parameters.AddWithValue("@expry", row.Cells["exp"].Value);
cmd.Parameters.AddWithValue("@dealername", row.Cells["dname"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
catch(SqlException ex) {
MessageBox.Show(ex.ToString());
}
MessageBox.Show("Records inserted.");
}
上面的代码正确插入数据但gridview会自动生成新行,这会产生错误enter image description here
答案 0 :(得分:2)
您可以在foreach行
之后添加此检查foreach (DataGridViewRow row in dataGridView1.Rows)
{
if(!row.IsNewRow)
{
....
}
}
但是我建议重构一下你的代码。基本上,您正在重建每个循环的连接,命令和所有参数。相反,您可以在开始循环之前构建连接,命令和参数。在循环内部仅更改参数值并执行查询
using (SqlConnection con = new SqlConnection(constring))
using (SqlCommand cmd = new SqlCommand("INSERT INTO stock VALUES(@productname, @packing,@totalquantity,@rate,@expry,@dealername)", con))
{
cmd.Parameters.Add("@productname", SqlDbType.NVarChar);
.... all the other parameters follow....
con.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if(!row.IsNewRow)
{
cmd.Parameter["@productname"].Value = row.Cells["pname"].Value);
....
.... set all other parameters with the row values
....
cmd.ExecuteNonQuery();
}
}
}
答案 1 :(得分:1)
您可以在插入前检查行是否为空。另请注意,所有插入只有一个连接:
string constring = @"Data Source=ZEE-PC\SQLEXPRESS;Initial Catalog=MyBill;Integrated Security=True;Pooling=False";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
foreach (var row in dataGridView1.Rows)
{
var productName = row.Cells["pname"].Value;
if (string.IsNullOrEmpty(productName))
continue;
using (SqlCommand cmd = new SqlCommand("INSERT INTO stock VALUES(@productname, @packing,@totalquantity,@rate,@expry,@dealername)", con))
{
cmd.Parameters.AddWithValue("@productname", );
cmd.Parameters.AddWithValue("@packing", row.Cells["packing"].Value);
cmd.Parameters.AddWithValue("@totalquantity", row.Cells["quantity"].Value);
cmd.Parameters.AddWithValue("@rate", row.Cells["rate"].Value);
cmd.Parameters.AddWithValue("@expry", row.Cells["exp"].Value);
cmd.Parameters.AddWithValue("@dealername", row.Cells["dname"].Value);
cmd.ExecuteNonQuery();
}
}
}
编辑:最好将IsNewRow
属性视为Steve
建议。
如果行是最后一行,则DataGridViewRow.IsNewRow返回true DataGridView,用于输入新的数据行; 否则,错误。