DataGridView中DataGridViewComboBoxColumn的一些相關應用(一)讓其值改變時觸發事件

 今天在csdn回一個帖子的時候看到一個DataGridView問題,需要觸發DataGridViewComboBoxCell中的事件才能夠解決.

打開vs試了下沒有找到能直接觸發DataGridViewComboBoxCell中combobox的值改變的事件,鬱悶了半天,仔細看MSDN上有解決示例,都怪自己沒有仔細看:

首先需要觸發第一個事件:CurrentCellDirtyStateChanged

並且在事件中調用DataGridView.CommitEdit 方法 [關於CommitEdit MSDN解釋如下:將當前單元格中的更改提交到數據緩存,但不結束編輯模式。 ]

這樣我們關心的那個事件CellValueChanged就能夠被順利觸發了

調用下MSDN上面對這個解決方式所提供的源碼僅供參考:)

 

// This event handler manually raises the CellValueChanged event
// by calling the CommitEdit method.
void dataGridView1_CurrentCellDirtyStateChanged(object sender,
    EventArgs e)
{
    if (dataGridView1.IsCurrentCellDirty)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

// If a check box cell is clicked, this event handler disables  
// or enables the button in the same row as the clicked cell.
public void dataGridView1_CellValueChanged(object sender,
    DataGridViewCellEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CheckBoxes")
    {
        DataGridViewDisableButtonCell buttonCell =
            (DataGridViewDisableButtonCell)dataGridView1.
            Rows[e.RowIndex].Cells["Buttons"];

        DataGridViewCheckBoxCell checkCell =
            (DataGridViewCheckBoxCell)dataGridView1.
            Rows[e.RowIndex].Cells["CheckBoxes"];
        buttonCell.Enabled = !(Boolean)checkCell.Value;

        dataGridView1.Invalidate();
    }
}

 
發佈了26 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章