Cell Value Changing Event ,c#

前端 未结 3 1820
陌清茗
陌清茗 2021-01-21 22:48

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 val

相关标签:
3条回答
  • 2021-01-21 23:01

    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");
    }
    
    0 讨论(0)
  • 2021-01-21 23:11

    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.

    0 讨论(0)
  • 2021-01-21 23:19

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题