如何在DataGrid中获取刚编辑的单元格的行和列索引

5

我在查找刚编辑的DataGrid单元格的行和列索引时遇到了问题。

我使用CellEditEnding事件来知道单元格何时被编辑。

到目前为止,我已经实现了以下功能:Col1包含属性DisplayIndex,该属性是所选列的索引,但我无法以相同的方式找到行索引。

    private void DataGridData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        DataGridColumn col1 = e.Column;
        DataGridRow row1 = e.Row;
    }
3个回答

7
我已经把它弄好了。这就是它的样子:
private void DataGridData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        DataGridColumn col1 = e.Column;
        DataGridRow row1 = e.Row;
        int row_index = ((DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1);
        int col_index = col1.DisplayIndex;
    }

0

回答晚了,但对于任何发现这个问题的人,通过将此事件添加到您的数据网格中,此代码将起作用:

private void dgMAQ_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
DependencyObject dep = (DependencyObject)e.EditingElement;
            string newText = string.Empty;

        //Check if the item being edited is a textbox
        if (dep is TextBox)
        {
            TextBox txt = dep as TextBox;
            if (txt.Text != "")
            {
                newText = txt.Text;
            }
            else
            {
                newText = string.Empty;
            }
        }
        //New text is the new text that has been entered into the cell

       //Check that the value is what you want it to be
        double isDouble = 0;
        if (double.TryParse(newText, out isDouble) == true)
        {

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

            if (dep == null)
                return;


            if (dep is DataGridCell)
            {
                DataGridCell cell = dep as DataGridCell;

                // navigate further up the tree
                while ((dep != null) && !(dep is DataGridRow))
                {
                    dep = VisualTreeHelper.GetParent(dep);
                }

                if (dep == null)
                    return;

                DataGridRow row = dep as DataGridRow;
                int rowIndex = row.GetIndex();

                int columnIndex = cell.Column.DisplayIndex;

        //Check the column index. Possibly different save options for different columns
                if (columnIndex == 3)
                {

                    if (newText != string.Empty)
                    {
                        //Do what you want with newtext
                    }
                }
}

0

如果没有“sender”参数,您可以尝试获取行索引:

 Convert.ToInt32(e.Row.Header)

结合 Patryk 回答的缩写形式,得到如下结果:

 private void DataGridData_CellEditEnding(DataGridCellEditEndingEventArgs e)
    {
        int col1 = e.Column.DisplayIndex;
        int row1 = Convert.ToInt32(e.Row.Header);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接