[英]Update SQL Server database from datagridview
I need to update my database on a local PC with SqlDataAdapter
. 我需要使用SqlDataAdapter
在本地PC上更新数据库。 The project is Windows Forms. 该项目是Windows窗体。 This method selects information from database and returns a DataTable
to be used as data source for a DataGridView
: 此方法从数据库中选择信息,并返回一个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;
}
This code is for update: 此代码用于更新:
public void setNewSizes()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
adapterSize.UpdateCommand = cmdBuilder.GetUpdateCommand();
conn.Open();
adapterSize.Update(receivedData.Tables[0]);
}
}
In receivedData
I have exactly the table need to update. 在receivedData
我确实需要更新表。 I get an error : 我得到一个错误:
connection string property has not been initialized 连接字符串属性尚未初始化
So, how can I fix it ? 那么,我该如何解决呢? Thanks. 谢谢。
You are redefining the variable adapterSize inside the clientSizes method effectively hiding the global variable defined at the class scope. 您将在clientSizes方法内重新定义变量adapterSize ,以有效地隐藏在类范围内定义的全局变量。
In this way the global variable defined at the class scope has no info about the parameter ID added to the internal variable and when you try to use it the exception is raised. 这样,在类范围内定义的全局变量就不会将有关参数ID的信息添加到内部变量中,并且当您尝试使用它时会引发异常。
Just remove the declaration of adapterSize and use the global variable 只需删除adapterSize的声明并使用全局变量
// SqlDataAdapter adapterSize = new SqlDataAdapter(commSelect);
adapterSize = new SqlDataAdapter(commSelect);
Side notes. 旁注。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.