首页 文章

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

提问于
浏览
0

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

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

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;        
}

它们都返回相同的索引 .

2 回答

  • 0

    尝试将单元格值转换为字符串并执行类似的操作(代码示例来自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);
                    }
                }
            }
        }
    
  • 0

    尝试使用 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*/
    }
    

相关问题