更改当前单元格后,C# 数据网格视图单元格值编辑将撤消



我希望你能帮助我。我没有通过谷歌搜索找到适合我问题的解决方案。

我有一个没有绑定数据的 DataGridView。当用户双击单元格时,他可以将新值写入单元格。根据更改,相邻单元格中的值也会更改。到目前为止,这工作正常。

现在我想设置一些条件,例如阈值,如果用户超出范围,则应更正编辑单元格中的值。相邻单元格中的值仍然计算正确,但用户编辑单元格中的值始终保持在用户输入值。

我已经尝试了BeginEdit((和CurrentCell的几种组合...,但总是相同的。

这是我对cellvalueChanged Event的实际代码:

private void dgSpotInfo_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (cellvaluechangend)
        {
            cellvaluechangend = false;
            int mod_Int_index = dgSpotInfo.Columns.IndexOf(dgSpotInfo.Columns["col_modifiedIntensity"]);
            dgSpotInfo.EditMode = DataGridViewEditMode.EditProgrammatically;
            dgSpotInfo.BeginEdit(true);
            int val;
            if (e.ColumnIndex == mod_Int_index) // if the modified Intensity value is changed
            {
                val = (Convert.ToInt32(dgSpotInfo[mod_Int_index, e.RowIndex].Value) - Convert.ToInt32(spot_analysis.GetFoundSpots[e.RowIndex].ModifiedIntensity));
                // here is tested if the value is too high
                if (Convert.ToInt32(dgSpotInfo[mod_Int_index, e.RowIndex].Value) > 255)
                {
                    // here is the problem, during debugging the value is displayed right, 
                    // but afterwards the current cell it is displayed as the too high value again
                    dgSpotInfo[mod_Int_index, e.RowIndex].Value = "255";
                    val = (Convert.ToInt32(dgSpotInfo[mod_Int_index, e.RowIndex].Value) - Convert.ToInt32(spot_analysis.GetFoundSpots[e.RowIndex].ModifiedIntensity));
                }
                dgSpotInfo.CurrentCell = dgSpotInfo[modifier_index, e.RowIndex];
                dgSpotInfo[modifier_index, e.RowIndex].Value = Convert.ToString(val);
            }
            dgSpotInfo.EndEdit();
            dgSpotInfo.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
            dgSpotInfo.ReadOnly = true;
        }
    }

这里是我的点击事件:

        private void dgSpotInfo_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        // Testing if the clicked cell is allowed to change
        if (((e.ColumnIndex == dgSpotInfo.Columns.IndexOf(dgSpotInfo.Columns["col_modifiedIntensity"])) || (e.ColumnIndex == dgSpotInfo.Columns.IndexOf(dgSpotInfo.Columns["col_Modifier"]))) && e.RowIndex >= 0)
        {
            dgSpotInfo.CurrentCell = dgSpotInfo[e.ColumnIndex, e.RowIndex];
            dgSpotInfo.ReadOnly = false;
            dgSpotInfo.BeginEdit(true);
            cellvaluechangend = true;
        } 
    }

我希望我描述我的问题可以理解,你可以帮助我。坦克!

如果有人有类似的问题:我通过添加 CellEndEdit 事件解决了这个问题。用户编辑单元格后,我现在在 CellEndEdit 事件处理程序中执行上述阈值验证。我不知道为什么,但也许是这样,在由编辑引起的事件处理程序中,您无法撤消编辑。

最新更新