當我使用以下代碼時,循環會迭代兩次,因爲「變量名'@projectName1'已經被聲明,所以我收到錯誤消息。變量名稱在查詢批處理或存儲過程中必須是唯一的。 「並重置datagridview中以及表中的表的所有值。其實我想通過選擇單元格來更新表單本身的DataGridView,它也應該反映在數據庫中。DataGridView正在更新數據庫
private void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = Helper.getconnection();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string myCmd = string.Empty;
foreach (DataGridViewRow myDgrow in dataGridView2.Rows)
{
myCmd = "Update Details set ProjectName='" + myDgrow.Cells["ProjectName"].Value + "', Description = '" + myDgrow.Cells["Description"].Value + "', DateStarted='" + myDgrow.Cells["DateStarted"].Value + "',TeamSize='" + myDgrow.Cells["TeamSize"].Value + "',Manager='" + myDgrow.Cells["Manager"].Value + "'";
cmd.Parameters.AddWithValue("@projectName1", myDgrow.Cells["ProjectName"].Value);
cmd.Parameters.AddWithValue("@Description1", myDgrow.Cells["Description"].Value);
cmd.Parameters.AddWithValue("@DateStarted1", myDgrow.Cells["DateStarted"].Value);
cmd.Parameters.AddWithValue("@TeamSize1", myDgrow.Cells["TeamSize"].Value);
cmd.Parameters.AddWithValue("@Manager1", myDgrow.Cells["Manager"].Value);
cmd.CommandText = myCmd;
cmd.ExecuteNonQuery();
dataGridView2.Update();
myCmd = string.Empty;
}
DataTable details = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
try
{
da.Update(details);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
爲什麼在地球上構建帶有字符串串聯值的命令,然後將值添加爲在任何地方都不使用的參數? – Bridge
好的,你說我應該只用一個。謝謝,讓我試試那個。 –
是的 - 類似這個答案的例子,你上週提出的同樣的問題:http://stackoverflow.com/a/18402568/ – Bridge