Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

Error when saving datagridview table (The name adapter does not exist in current context)

$
0
0

First part of code (pulling data into datagridview) works fine, then I tried to add code for button Save.

Basically, I just modify the code from this thread, not sure why it shows error message. How can the program know btnSave_Click  AdapterTest refers tocbxModel_SelectedIndexChanged_Click  AdapterTest?

I have removed Cn.Close , should it be removed? Should I need to keep Cn opened when running btnSave_Click?

Thanks.

//Refresh DataGridView table when combo box item changed
private void cbxModel_SelectedIndexChanged(object sender, EventArgs e)
{
    if ((string.IsNullOrEmpty(cbxModel.Text)) || cbxModel.SelectedIndex == -1)
    {
        //Do nothing
    }
    else
    {

        OdbcDataAdapter AdapterTest = null;
        DataSet dSetTest = null;

        OdbcConnection Cn = new OdbcConnection(ConnectionString);
        Cn.Open();

        AdapterTest = new OdbcDataAdapter("SELECT * from TableName WHERE FieldA = cbxModel.Text", Cn);
        dSetTest = new DataSet();
        AdapterTest.Fill(dSetTest);

        datagridview1.DataSource = dSetTest.Tables[0];

        //Cn.Close();


    }
}

//Above code works fine before adding btnSave code


//When user makes updates to datagridviewtable, save the changes to database
private void btnSave_Click(object sender, EventArgs e)
{
    OdbcCommandBuilder cbTest = new OdbcCommandBuilder(AdapterTest);
    try
    {
        AdpterTest.Update(dSetTest);
    }
    catch (OdbcException ex)
    {
        MessageBox.Show(ex.Message);
    }
}



Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>