在datagridview中比较旧单元格和新单元格值

本文关键字:单元格 datagridview 比较 | 更新日期: 2023-09-27 18:10:25

我有一个DataGridView。我必须比较旧的和新的单元格值,并执行进一步的操作。

我尝试使用以下代码与Cell Leave, CellValidating事件进行比较,

private void TestGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    int currentCell = TestGrid.CurrentCell.ColumnIndex;
    var oldCellValue = TestGrid[e.ColumnIndex, e.RowIndex].Value;
    var newValue = e.FormattedValue;
}

当我尝试点击不同的单元格时,它返回我的旧值和新值,例如:1000。

请让我知道,如果有任何其他事件,我可以达到预期的行为。另外,如果我必须比较旧的和新的单元格行或列索引,然后如何进行?

private void TestGrid_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    int currentCell = TestGrid.CurrentCell.ColumnIndex;
    int oldCell = e.ColumnIndex;        
}

它们返回相同的索引。

在datagridview中比较旧单元格和新单元格值

尝试将单元格值转换为字符串,并执行类似的操作(代码示例来自MSDN)。希望对你有帮助。

// Iterate through the SelectedCells collection and sum up the values. 
for (counter = 0;
    counter < (DataGridView1.SelectedCells.Count); counter++)
{
    if (DataGridView1.SelectedCells[counter].FormattedValueType ==
        Type.GetType("System.String"))
    {
        string value = null;
        // If the cell contains a value that has not been commited, 
        // use the modified value. 
        if (DataGridView1.IsCurrentCellDirty == true)
        {
            value = DataGridView1.SelectedCells[counter]
                .EditedFormattedValue.ToString();
        }
        else
        {
            value = DataGridView1.SelectedCells[counter]
                .FormattedValue.ToString();
        }
        if (value != null)
        {
            // Ignore cells in the Description column. 
            if (DataGridView1.SelectedCells[counter].ColumnIndex !=
                DataGridView1.Columns["Description"].Index)
            {
                if (value.Length != 0)
                {
                    SelectedCellTotal += int.Parse(value);
                }
            }
        }
    }

尝试使用DataGridViewEditedFormattedValue属性。测试了这个,我看到了不同的值:

private void TestGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    int currentCell = TestGrid.CurrentCell.ColumnIndex;
    var oldValue = TestGrid[e.ColumnIndex, e.RowIndex].Value;
    var newValue = TestGrid[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
    /* Perform some logic here*/
}