CellEditEnding: How to find value and column

Nov 27, 2008 at 6:24 PM
I have a DataGrid where I would like to change the value of one cell based on the user changing another. I thought I would use the CellEditEnding event, but I'm havinging difficulty finding the new value and what column I'm at. I assume I can get the new value from e.EditingElement, but how? And e.Column: how do I find out which one it is? Any help would be appreciated.
Nov 27, 2008 at 7:27 PM
See if this helps:

private void grid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
MyRecord rec = e.Row.Item as MyRecord;  // Current Record
TextBox t = e.EditingElement as TextBox;  // Assumes columns are all TextBoxes
DataGridColumn dgc = e.Column;

Debug.WriteLine(t.Text .ToString());
Debug.WriteLine(dgc.Header.ToString());
}

Dec 26, 2014 at 10:54 AM
Edited Dec 26, 2014 at 10:54 AM
I had the same issue, and after a little research came up with the following function. :)


public static string GetDataGridCellValue(FrameworkElement fe, string ColumnType)
{
    string value = "";
    switch (ColumnType)
    {
        case "DataGridTextColumn":
            TextBox t = fe as TextBox;
             value = t.Text;
            break;
        case "DataGridComboBoxColumn":
            ComboBox c = fe as ComboBox;
            value = c.Text;
            break;
        case "DataGridHyperlinkColumn":
            TextBox te = fe as TextBox;
            value = te.Text;
            break;
        case "DataGridCheckBoxColumn":
            TextBox text = fe as TextBox;
            value = text.Text;
            break;
        default:
            TextBox tex = fe as TextBox;
            value = tex.Text;
            break;
    }

    return value;
}

You can call this like below (attached to the CellEditEnding event for the dataGrid):

private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {

        string columnType = e.Column.GetType().Name;


        string result = GetDataGridCellValue(e.EditingElement, columnType);

     }