我有DataGridView
包含数据。这是图片:
当我成功地将DataGridView
中的数据插入表格时,结果就像这样
qty和subtotal中有一个零数字。当我将数据从DataGridView
插入表
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
con.execute("INSERT INTO SalesDetail VALUES('" + txtID.Text + "','"
+ dataGridView1.Rows[i].Cells["Column7"].Value + "','"
+ dataGridView1.Rows[i].Cells["Column3"].Value + "','"
+ dataGridView1.Rows[i].Cells["Column5"].Value + "','"
+ dataGridView1.Rows[i].Cells["Column6"].Value + "')");
//con.execute("UPDATE KerupukDetail SET currentStock = currentStock - '" + dataGridView1.Rows[i].Cells["Column3"].Value + "' WHERE kerupukID='" + dataGridView1.Rows[i].Cells["Column7"].Value + "' and fryingID='" + textBoxriedID.Text + "'");
}
我有Class
Connection
来连接数据库:
class Connect
{
SqlConnection con;
public Connect()
{
String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + @"\Database1.mdf;Integrated Security=True;User Instance=True";
con = new SqlConnection(connectionString);
}
public DataTable executeSelect(String query)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
con.Close();
return dt;
}
public void execute(String query)
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
如何修复此代码并删除零号?
注意:在一个SalesID中可以包含一个或多个kerupukID。
txtID
是SalesID
答案 0 :(得分:0)
您需要小于dataGridView1.Rows.Count-1,因为您有额外的行用于在datagridview中添加新行。
或者您可以检查isNewRow并仅在isNewRow返回false时执行您的插入。
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (!dataGridView1.Rows[i].IsNewRow)
{
//perform your insert
}
}