0

In my Datagrid I allow users to edit some cells, after editing these cells I would like to commit the changes to the database (on enter). I am having troubles finding resources online to get this going.

I use an event called:

CellEditEnding but the event only provides me with the Row and Col how of the changed cell. How do I use these to find the cell itself and get the value?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
user781439
  • 247
  • 2
  • 5
  • 19

1 Answers1

4

you could use this function found in this link

public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
    if (row != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }

        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        return cell;
    }
    return null;
}

and call it from your event handler :

object cellvalue = DataGridCell(yourgrid, e.Row, e.Column.DisplayIndex).GetValue;

this function is also called within the GetCell() function

public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }
Abdusalam Ben Haj
  • 5,343
  • 5
  • 31
  • 45