我正在尝试创建一个帐单。我在sql-server中有两个表。文本框应将日期插入表1,并将datagridview插入表2。
我没有收到任何错误,但是我有一个生成自动编号的文本框,并且在每个编号下datagridview中应该有多行。
下面的代码仅保存表中的最后一行。 This is my billing form.
您可以检查代码并告诉我哪里出了问题吗?
con = new SqlConnection("data source=localhost;initial catalog=testDb;integrated security=true");
con.Open();
cmd = new SqlCommand(@"select CashirReport.ReportId,CashirReport.ReportNumber,CashirReport.ReportDate ,
CashirReportDetails.SerialNumber,
CashirReportDetails.RefDetails,CashirReportDetails.Amount from CashirReport
inner join CashirReportDetails on CashirReport.ReportId=CashirReportDetails.ReportDetailsNumber", con);
da = new SqlDataAdapter();
da.SelectCommand = cmd;
dt = new DataTable();
da.Fill(dt);
}
private void btnsave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvDetails.Rows.Count - 1; i++)
{
cmd = new SqlCommand(@"insert into CashirReport(ReportDate,Total)values(@ReportDate,@Total);
insert into CashirReportDetails(SerialNumber,RefDetails,Amount)values(@SerialNumber,@RefDetails,@Amount)",con);
cmd.Parameters.AddWithValue("@ReportDate", SqlDbType.Date).Value = dtDate.Value.Date;
cmd.Parameters.AddWithValue("@Total", SqlDbType.Money).Value = txtAmount.Text;
cmd.Parameters.AddWithValue("@SerialNumber", dgvDetails.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@RefDetails", dgvDetails.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@Amount", dgvDetails.Rows[i].Cells[2].Value);
}
cmd.ExecuteNonQuery();
答案 0 :(得分:0)
只需将cmd.ExecuteNonQuery();
放入for循环内即可:
private void btnsave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvDetails.Rows.Count - 1; i++)
{
cmd = new SqlCommand(@"insert into CashirReport(ReportDate,Total)values(@ReportDate,@Total);
insert into CashirReportDetails(SerialNumber,RefDetails,Amount)values(@SerialNumber,@RefDetails,@Amount)",con);
cmd.Parameters.AddWithValue("@ReportDate", SqlDbType.Date).Value = dtDate.Value.Date;
cmd.Parameters.AddWithValue("@Total", SqlDbType.Money).Value = txtAmount.Text;
cmd.Parameters.AddWithValue("@SerialNumber", dgvDetails.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@RefDetails", dgvDetails.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@Amount", dgvDetails.Rows[i].Cells[2].Value);
//inside the for loop
cmd.ExecuteNonQuery();
}
}