[英]Get Value of a specific cell in DataGrid
I have a DataGrid. 我有一个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. 为此,我找到了该单元格的rowindex。 And I want the data from second column. 我想要第二列的数据。 So far my code in KeyDown event of datagrid looks like below : 到目前为止,我在datagrid的KeyDown事件中的代码如下所示:
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. 我已经在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? 假设我要查找属于第5行和第4列的单元格的值,那么如何找到呢?
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.