Skip to content
Advertisement

update command C# DataGridView to SQL

I’m attempting to update a SQL table from C# project datagridview “Work_Table”. However when I attempt to make the update I get this error

“Update unable to find TableMapping [‘Work_Table’] or DataTable ‘Work_Table'”

Any ideas?

Here is my code below:

        try
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                string query = @"Select * from person.addresstype";

                SqlCommand cmd = new SqlCommand(query, conn);

                SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);

                DataSet ds = new DataSet();

                dAdapter.Update(ds, "Work_Table");

                MessageBox.Show("Saved");
            }
        }
        catch (Exception ee)
        {
            MessageBox.Show(ee.Message);

Advertisement

Answer

You need to retrieve the DataTable from the .DataSource property of the grid. This will have the information on what was added, updated and deleted.

You can skip the command and pass the select string and connection string directly to the DataAdapter constructor.

Create a CommandBuilder to provide the Insert, Update and Delete text for the DataAdapter.Update. Pass the DataAdapter to the constructor of the CommandBuilder.

    private string connString = "Your connection string";
    private void button1_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)dataGridView1.DataSource;
        try
        {
            using (SqlDataAdapter dAdapter = new SqlDataAdapter("Select * from person.addresstype", connString))
            using (SqlCommandBuilder cb = new SqlCommandBuilder(dAdapter))
            {
                dAdapter.Update(dt);
            }
            MessageBox.Show("Saved");
        }
        catch (Exception ee)
        {
            MessageBox.Show(ee.Message);
        } 
    }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement