Vishal Vishal - 1 month ago 22
C# Question

Get Value of a specific cell in DataGrid

I have a DataGrid. Now I want to have the data from a particular cell for some comparison purpose. For that I have found the rowindex of that cell. And I want the data from second column. So far my code in KeyDown event of datagrid looks like below :

DependencyObject dep = (DependencyObject)e.OriginalSource;

while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}

if (dep == null)
return;

if (dep is DataGridCell)
{
//cancel if datagrid in edit mode
maindg.CancelEdit();


//Check if selected cell is on second column and last row
if (maindg.CurrentColumn.DisplayIndex == 1)
{
DependencyObject depObj = dep;

//Find Row to which selectedCell belongs
while ((depObj != null) && !(depObj is DataGridRow))
{
depObj = VisualTreeHelper.GetParent(depObj);
}

DataGridRow selectedCellRow = depObj as DataGridRow;
if (FindRowIndex(selectedCellRow) == maindg.Items.Count - 1)
{
if (Here I want to check if cell's value is null or empty)
{
btnSave.Focus();
return;
}
}
}
}


I have searched for this question on google. But everywhere I get the value of the selected cell. Suppose I want to find the value of a cell which belongs to row 5 and column 4, then how can I find that?

Answer

You could try the code below, it will get you the cell.

if (selectedCellRow != null)
{
    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(selectedCellRow);
    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
    var cellValue = cell.Content;
}