2017-03-02 22 views
0

C#,WinForms移动DataGridView1.CurrentCell和BeginEdit不起作用。如果我使用Tab#

也许这是一个愚蠢和微不足道的问题,但我不能出去! 我有一个DataGridView1 4列。我检查列1中每行的值是否与列2中前一行的值相同。如果是,则显示一个MessageBox告诉我...并且我想将焦点置于其中的单元格有刚刚输入的双重值。因此我写了这段代码:

private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs cella) 
{ 
    if (cella.RowIndex > 0 && cella.ColumnIndex == 1) 
    { 
     var PrevCell = DataGridView1.Rows[cella.RowIndex - 1].Cells[2].Value.ToString(); 
     if (DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex].Value.ToString() == PrevCell) 
     { 
      MessageBox.Show("Amount already exists. Change the current value or the previous occurrence", "Double value, already inserted", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      DataGridView1.CurrentCell = DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex]; 
      DataGridView1.BeginEdit(true); 
      //only a test: 
      //return; 
      } 
     } 
    } 
} 

CurrentCell工作正常。问题是,当我按下Tab键移动到下一个单元格(或者我用鼠标点击下一个单元格),因此即使BeginEdit将我置于右侧,也会发生CellEndEdit事件单元格让我编辑该值,只要我再次按下Tab键,它将在下一个单元格中移动已更改的值。看起来在显示MessageBox之前按下的Tab仍保留在内存中。

当我正在写一个双精度值,消息框出现 When I'm writing a double value, and MessageBox appears

当CurrentCell和BeginEdit导致我在正确的细胞改变双重价值 When the CurrentCell and BeginEdit lead me in the correct cell to change the double value

在活动结束

At the end of the Event

如何处理这个问题的任何想法?

+0

什么是消息框的翻译? –

+0

我只在代码中的MessageBox中翻译了它:'Quantitàgiàpresente。 Modifica l'attuale valore o l'occorrenza precedente' ='金额已经存在。当Valore doppio,giàinserito' ='Double value,already inserted'时,改变当前值或前一个事件。 – Wiccio

回答

1

您需要选择该单元并在之后调用BeginEdit方法CellEndEdit事件发生。要做到这一点,将该代码包装在BeginInvoke块中:

this.BeginInvoke(new Action(() => { 
    DataGridView1.CurrentCell = DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex]; 
    DataGridView1.BeginEdit(true); 
})); 
+0

我从来没有使用'Begin.Invoke'方法和代理'Action'直到现在......但是我必须更好地研究它,因为您的解决方案能够工作!非常感谢。 ;-) – Wiccio