How i can get result on cell leave event of datagrid view?

10.2k views Asked by At

Here is my code That displays multiplication of Rate * Supply column values and assign it to the Amount column in data grid view :

try
{
Query = "Select  id,Code,Description,Rate,Cust_Id,Supply,Empty,Amount,Received from Items where Cust_Id='" + GlobalVars.id + "'";
adap = new SQLiteDataAdapter(Query, GlobalVars.conn);
ds = new DataSet();
adap.Fill(ds, "Items");
dtgVOuchers.DataSource = ds.Tables[0];
dtgVOuchers.Columns["Cust_Id"].Visible = false;
dtgVOuchers.Columns["id"].Visible = false;
ds.Tables[0].Columns["id"].AutoIncrement = true;
ds.Tables[0].Columns["id"].AutoIncrementSeed = itmcount + 1;
ds.Tables[0].Columns["id"].AutoIncrementStep = 1;
ds.Tables[0].Columns["Cust_Id"].DefaultValue = GlobalVars.id;

dtgVOuchers.Columns["Code"].ReadOnly = true;
dtgVOuchers.Columns["Description"].ReadOnly = true;
dtgVOuchers.Columns["Rate"].ReadOnly = true;
dtgVOuchers.Columns["Amount"].ReadOnly = true;
 foreach (DataGridViewRow row in dtgVOuchers.Rows)
  {
   row.Cells[dtgVOuchers.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Rate"].Index].Value) * Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Supply"].Index].Value));

  } 
 dtgVOuchers.Refresh();
}

This multiplication is done if i double click on "Amount" cell in datagrid view and get resultant amount in corresponding cell . What i want is to get multiplication result in corresponding cell on cell leave event .It means when user leave the cell of "Supply" or "Rate" by typing value then this event provide the update to corresponding "Amount" cell so that user don't need double click on cell where he wants result. Can somebody guide me how i can accomplish this ?

1

There are 1 answers

1
King King On BEST ANSWER

You should handle the CellValueChanged instead, although handling that event may bring you the same effect (if user changes the cell value via UI, the CellValueChanged is fired only after the cell value is changed and loses focus):

private void dtgVOuchers_CellValueChanged(object sender, DataGridViewCellEventArgs e){
  var cell = dtgVOuchers[e.ColumnIndex, e.RowIndex];
  if(cell.OwningColumn.Name == "Rate" || cell.OwningColumn.Name == "Supply"){
    //update the Amount cell
    cell.OwningRow.Cells["Amount"].Value = Convert.ToDecimal(cell.OwningRow.Cells["Rate"].Value) *
                                          Convert.ToDecimal(cell.OwningRow.Cells["Supply"].Value);
  }
}

I suppose the value type of the Amount cell is decimal, you can change the Convert.ToDecimal to the corresponding converter of the data type.