Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datagridview cell edit and save functionality in windows forms?

I'm working on datagridview in c# windows forms application and I'm loading the data from the database, now i want the user to be able to able to edit the cell value and save the value to the database, how to edit the cell value and how can i save the value to the database?

  SqlConnection con = new SqlConnection("user id=sa;password=123;database=employee");
  SqlDataAdapter da = new SqlDataAdapter("select * from UserReg", con);
  DataSet ds = new DataSet();
  da.Fill(ds, "p");
  dataGridView1.DataSource = ds.Tables["p"];
like image 813
adityaa Avatar asked Feb 17 '23 04:02

adityaa


1 Answers

One of the way to update a database with DataGridView is using of DataGridView's events:

DataGridView.CellBeginEdit

DataGridView.CellValidating

DataGridView.CellEndEdit

Let say: private DataGridView dgv; Add handlers of events

dgv.CellBeginEdit += dgv_CellBeginEdit;
dgv.CellValidating += dgv_CellValidating;
dgv.CellEndEdit += dgv_CellEndEdit;

private void dgv_CellBeginEdit(Object sender, DataGridViewCellCancelEventArgs e)
{
     //Here we save a current value of cell to some variable, that later we can compare with a new value
    //For example using of dgv.Tag property
    if(e.RowIndex >= 0 && e.ColumnIndex >= 0)
    {
        this.dgv.Tag = this.dgv.CurrentCell.Value;
        //Or cast sender to DataGridView variable-> than this handler can be used in another datagridview
    }
}

private void dgv_CellValidating(Object sender, DataGridViewCellValidatingEventArgs e)
{
    //Here you can add all kind of checks for new value
    //For exapmle simple compare with old value and check for be more than 0
    if(this.dgv.Tag = this.dgv.CurrentCell.Value)
        e.Cancel = true;    //Cancel changes of current cell
    //For example used Integer check
    int32 iTemp;
    if (Int32.TryParse(this.dgv.CurrentCell.Value, iTemp) = True && iTemp > 0)
    {
        //value is ok
    }
    else
    {
        e.Cancel = True;
    }
}

Private Sub dgvtest1_CellEndEdit(Object sender, DataGridViewCellEventArgs e)
{
    //Because CellEndEdit event occurs after CellValidating event(if not cancelled)
    //Here you can update new value to database
}
like image 102
Fabio Avatar answered Feb 20 '23 05:02

Fabio