簡體   English   中英

datagridview CellEndEdit觸發兩次

[英]datagridview CellEndEdit fires twice

我在datagridview的CellEndEdit事件中遇到了一些問題。 雖然我了解問題的實質所在,但任何繞過該問題的嘗試似乎都失敗了。

基本上,在CellEndEdit事件中,我有一個datagridview,我對數據庫進行檢查以確保該條目不是重復的。 如果是這樣,我會在消息框中提示用戶告訴他們他們不能輸入重復項,然后以編程方式將值更改回其原始狀態/值,並將單元格返回到“編輯”狀態。

我的理解是,我以編程方式更改值的事實是事件觸發兩次的原因。 為了規避,我首先進入事件時設置了一個標志,然后提示+設置+重新編輯,然后將該標志設置為false。 這行不通...任何人都可以告訴我原因或如何實現這一目標?

這是事件代碼:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if(e.ColumnIndex == this.dataGridView1.Columns["Name"].ColumnIndex)
    {
        if(!this.CellBeingEdited)
        {
            string NewName = this.dataGridView1.Rows[e.RowIndex].Cells["Name"].Value.ToString();
            //-== DATABASE CODE REMOVED ==-
            bool IsDuplicate = ...;
            if(IsDuplicate)
            {
                MessageBox.Show("Cannot have duplicate item names at this level!");
                this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells["Name"];
                this.CellBeingEdited = true;
                this.dataGridView1.CurrentCell.Value = this.LastEditedRowName;
                this.CellBeingEdited = false;
                this.dataGridView1.BeginEdit(false);
                return;
            }
        }
    }
}

當我連續編輯一個值時,這段代碼不會觸發兩次:

   private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
   {
        string test = "test";
        if (this.dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString() == test)
        {
            this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[0];
            this.dataGridView1.CurrentCell.Value = "not test";
            this.dataGridView1.BeginEdit(false);
            return;
        }
    }

也許您在其他地方打電話給該活動?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM