Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Datagrid cell original value with edited value in CellEditEnding event

I have a totals variable that is updated based on the numbers entered by the user in my Datagrid rows. I would like to update that value on changing each row cell. This is what I've done so far:

private void QuotationDG_CellEditEnding(object sender, 

DataGridCellEditEndingEventArgs e)
{

    int ColumnIndex = e.Column.DisplayIndex;

    Double amount= Double.Parse(((TextBox)e.EditingElement).Text);
    Cat1SubTotal += amount;
    GrandTotal += amount;
}

This code adds up the amount each time the user enters a new value. However, if the user edited the existing value then this would add up the new value without removing the old value thus will show incorrect totals.

I need to do something like this:

Cat1SubTotal += (NewValue-OriginalValue)
like image 390
user3340627 Avatar asked Jan 09 '23 02:01

user3340627


1 Answers

Handle the BeginningEdit event and store the value in a private variable when user begins to edit. Then compare it to the new value handled in the CellEditEnding event.

 public partial class MainWindow : Window
{
    private ViewModel VM { get; set; }
    private DataGridCellInfo activeCellAtEdit { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        this.VM = new ViewModel();
        this.DataContext = this.VM;
    }

    private void MyDataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        this.activeCellAtEdit = MyDataGrid.CurrentCell;
    }

    private void MyDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
         //assumes columns are all TextBoxes
        TextBox t = e.EditingElement as TextBox; 
        string editedCellValue = t.Text.ToString();

        //assumes item property bound to datagrid is of type string
        string originalValue = activeCellAtEdit.Item.SomeStringProperty;

        //compare strings
        if(editedCellValue != originalValue)
        {
            //do something
        }

    }

}
like image 115
d3ssy Avatar answered Jan 14 '23 22:01

d3ssy