[英]Saving only the first row of a gridview to DB
我需要將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;
}
}
}
}
也許你可以參考這個鏈接
根據該帖子,您可以:
您的代碼只保存每單擊一次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();
可能下面的代碼是您的問題,因為您在第一個循環結束時就將它們弄清楚了。 如果清除了這些控件的值,則第二時間循環將不會運行。
不要把它們弄清楚再檢查一次。
((TextBox)(row.FindControl("txtStyle"))).Text = string.Empty;
((TextBox)(row.FindControl("txtMSMV"))).Text = string.Empty;
((TextBox)(row.FindControl("txtTSMV"))).Text = string.Empty;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.