I need to update my database on a local PC with SqlDataAdapter
. The project is Windows Forms. This method selects information from database and returns a DataTable
to be used as data source for a 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. 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.
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.
Just remove the declaration of adapterSize and use the global variable
// SqlDataAdapter adapterSize = new SqlDataAdapter(commSelect);
adapterSize = new SqlDataAdapter(commSelect);
Side notes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.