Nagendra Kumar
Nagendra Kumar

Reputation: 654

Cell Value Changing Event ,c#

I have a DataGridView in which there are 3 columns; Quantity, Rate and Amount.
The DataGridView is Editable. When I enter a value in the Rate Column then immediately the value should be changed in Amount.

Amount=Qty*rate

It is happening, but when I click on any other cell, I want that when I enter any value in Rate it should be multiplied with Quantity and be reflected immediately in Amount without changing the cell.

Upvotes: 2

Views: 33177

Answers (3)

mehta.samarth
mehta.samarth

Reputation: 21

I have found no event that can handle the value of cell change properly.

You must convert the editable cell into a Textbox, then provide the changed event on it.

This is the code that i found while browsing one of the MSDN Forums:

http://social.msdn.microsoft.com/Forums/windows/en-US/a56ac5c1-e71f-4a12-bbfa-ab8fc7b36f1c/datagridview-text-changed?forum=winformsdatacontrols

I am also adding the code here:

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

{

   if (dataGridView1.CurrentCell.ColumnIndex == 0)
   {

      TextBox tb = (TextBox)e.Control;
      tb.TextChanged += new EventHandler(tb_TextChanged);
   }
}

void tb_TextChanged(object sender, EventArgs 
{
   MessageBox.Show("changed");
}

Upvotes: 1

Dmitrii Erokhin
Dmitrii Erokhin

Reputation: 1347

As it was mentioned by Sachin Shanbhag you should use both DataGridView.CurrentCellDirtyStateChanged and DataGridView.CellValueChanged events. In DataGridView.CurrentCellDirtyStateChanged you should check whether the user is modifying the right cell (Rate in your case) and then execute DataGridView.CommitEdit method. Here is some code.

private void YourDGV_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (YourDGV.CurrentCell.ColumnIndex == rateColumnIndex)
    {
        YourDGV.CommitEdit(DataGridViewDataErrorContexts.Commit);                        
    }
}

private void YourDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == rateColumnIndex)
    {
        DataGridViewTextBoxCell cellAmount = YourDGV.Rows[e.RowIndex].Cells[amountColumnIndex];
        DataGridViewTextBoxCell cellQty = YourDGV.Rows[e.RowIndex].Cells[qtyColumnIndex];
        DataGridViewTextBoxCell cellRate = YourDGV.Rows[e.RowIndex].Cells[rateColumnIndex];
        cellAmount.Value = (int)cellQty.Value * (int)cellRate.Value;
    }
}

Upvotes: 7

Alex Essilfie
Alex Essilfie

Reputation: 12613

If you really want to update the value without changing cells (as in on the fly), you'll have to handle the DataGridView.KeyPress event and check for which cell is being updated.

If that's too much of a hassle, use the DataGridView.CellValueChanged event. It's simpler to implement than the KeyPress event.

Upvotes: 0

Related Questions