我需要将gridview中的多行保存到数据库中。但是,我当前的代码仅保存第一行。我徘徊为什么它没有循环我的foreach线。我执行预期任务时缺少的代码是什么。谢谢!
我的活动是
protected void btnSaveAll_Click(object sender, EventArgs e)
{
using (SqlConnection conn = DB_Connect.GetConn())
{
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.StoredProcedure;
foreach (GridViewRow row in grdStyle.Rows)
{
if (Convert.ToString((row.FindControl("txtStyle") as TextBox).Text.Trim()) == string.Empty)
{
WebMsgBox.Show("Style cannot be empty.");
return;
}
if (Convert.ToString((row.FindControl("txtMSMV") as TextBox).Text.Trim()) == string.Empty)
{
WebMsgBox.Show("MSMV cannot be empty.");
return;
}
if (Convert.ToString((row.FindControl("txtTSMV") as TextBox).Text.Trim()) == string.Empty)
{
WebMsgBox.Show("TSMV cannot be empty.");
return;
}
string TeamID = Convert.ToString((row.FindControl("TeamID") as Label).Text.Trim());
string Style = Convert.ToString((row.FindControl("txtStyle") as TextBox).Text.Trim());
string MSMV = Convert.ToString((row.FindControl("txtMSMV") as TextBox).Text.Trim());
string TSMV = Convert.ToString((row.FindControl("txtTSMV") as TextBox).Text.Trim());
newCmd.CommandText = "[DailyProductionOutput].[dbo].[sp_InsertTeamStyle]";
newCmd.Parameters.Add("@TeamID", SqlDbType.Int).Value = TeamID;
newCmd.Parameters.Add("@CompanyID", SqlDbType.Int).Value = companyID;//global variable
newCmd.Parameters.Add("@Style", SqlDbType.NVarChar).Value = Style;
newCmd.Parameters.Add("@MSMV", SqlDbType.Decimal).Value = MSMV;
newCmd.Parameters.Add("@TSMV", SqlDbType.Decimal).Value = TSMV;
try
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
newCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
WebMsgBox.Show("Saving failed." + ex);
}
conn.Close();
((TextBox)(row.FindControl("txtStyle"))).Text = string.Empty;
((TextBox)(row.FindControl("txtMSMV"))).Text = string.Empty;
((TextBox)(row.FindControl("txtTSMV"))).Text = string.Empty;
}
}
}
}
答案 0 :(得分:1)
也许您可以参考this link
根据该帖子,你可以:
您的代码仅保存每个点击的btnSaveAll的最后一行,因为您没有遵循此条件。
就像这样:
SqlConnection conn = DB_Connect.GetConn();
conn.Open();
....
using(SqlCommand ....)
{
foreach (GridViewRow row in GridView1.Rows)
{
.....
your transaction here
.....
newCmd.Parameters.Clear();
...filling parameter
newCmd.ExecuteNonQuery();
}
}
conn.Close();
答案 1 :(得分:0)
可能是以下代码是您的问题,因为您在第一次循环结束时将它们清除。如果清除了那些控件的值,则第二次循环将不会运行..
不要说清楚并再次检查..
@Autowired