Updating records from Datagridview

149 Views Asked by At

I am trying to update records from a DataGrid but I am getting the following error message:

Update requires valid UpdateCommand when passed DataRow collection with modified rows

Here is My code:

private void btnUpdate_Click(object sender, EventArgs e)
{
    System.Data.DataTable dt = ds.Tables["tblImpi"];
    this.impdg.BindingContext[dt].EndCurrentEdit();
    this.dataAdapter.Update(dt);

    MessageBox.Show("Update Successful");
}
1

There are 1 best solutions below

0
Syed Farjad Zia Zaidi On

Try this:

SqlDataAdapter adapter;
DataSet ds;
public void ReadData()
{
    this.ds = new DataSet())
    this.adapter = new SqlDataAdapter(query, conString))
    adapter.Fill(thisds, "TABLE1");
    this.ds.AcceptChanges();
    this.dataGridView1.DataSource = ds.DefaultViewManager;
}

public void SaveData()
{
    using (DataSet changes = this.ds.GetChanges())
    {
        if (changes != null)
        {
            int updatedRows = this.dataAdapter.Update(changes);
            this.ds.AcceptChanges();
        }
    }
}

private void btnUpdate_Click(object sender, EventArgs e)
{
    SaveData();
}

For understanding DataGrid Control