Search code examples
datagridviewinsertion

Insertion of rows from DatagridView into Database on Row change Event


I want to insert rows into SQL table from Datagridview in this way -> Whenever any new row is inserted in the Datagridview ,that row is automatically saved in the database when the user goes in another row .And if it is not a new row then nothing should happen.Means there should be some Event which is fired on Row change. Please can any1 tell which is appropriate event to do this thing. -Thanx in advance.


Solution

  • You should do this on the RowValidating event.

    If the insertion fails, you can set the eventargs's Cancel property to true, and notify the user of the error.

    Example:

    void dataGridView1_RowValidating(object sender, 
       DataGridViewCellCancelEventArgs e)
    {
      try
      {
        // do something to insert/update row
      }
      catch (Exception ex)
      {
        e.Cancel = true;
        dataGridView1.Rows[e.RowIndex].ErrorText = ex.Message;
      }
    }