[英]Update SQL Server database from datagridview
我需要使用SqlDataAdapter
在本地PC上更新數據庫。 該項目是Windows窗體。 此方法從數據庫中選擇信息,並返回一個DataTable
用作DataGridView
數據源:
static string querySelect = "select * from [customers_Sizes] where ID_customers = @ID_customers";
private DataSet recivedData;
static public SqlDataAdapter adapterSize = new SqlDataAdapter(querySelect, connectionString);
SqlCommandBuilder cmdBuilder;
public DataTable clientSizes(int ID)
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand commSelect = new SqlCommand(querySelect, conn);
commSelect.Parameters.AddWithValue("@ID_customers", ID);
adapterSize = new SqlDataAdapter(commSelect);
cmdBuilder = new SqlCommandBuilder(adapterSize);
recivedData = new DataSet();
conn.Open();
adapterSize.Fill(recivedData);
table = recivedData.Tables[0];
}
return table;
}
此代碼用於更新:
public void setNewSizes()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
adapterSize.UpdateCommand = cmdBuilder.GetUpdateCommand();
conn.Open();
adapterSize.Update(receivedData.Tables[0]);
}
}
在receivedData
我確實需要更新表。 我得到一個錯誤:
連接字符串屬性尚未初始化
那么,我該如何解決呢? 謝謝。
您將在clientSizes方法內重新定義變量adapterSize ,以有效地隱藏在類范圍內定義的全局變量。
這樣,在類范圍內定義的全局變量就不會將有關參數ID的信息添加到內部變量中,並且當您嘗試使用它時會引發異常。
只需刪除adapterSize的聲明並使用全局變量
// SqlDataAdapter adapterSize = new SqlDataAdapter(commSelect);
adapterSize = new SqlDataAdapter(commSelect);
旁注。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.