简体   繁体   中英

Update SQL Server database from datagridview

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.

  1. It is not clear why you have defined all those globals variable with the static keyword. If there is no compelling reason to do that, I suggest to remove the static keyword and just have class local private variables.
  2. There is no need to initialize the SqlDataAdapter when you declare it and then again inside the clientSizes method, just use the initialization inside the method (of course you need to be sure that nowhere else you use that adapter before calling clientSizes
  3. You are calling the adapterSize.Fill two times. Again there is no need of the second call. The fill of the DataSet is enough to read the data

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM