我認爲你最好的選擇是使用RowValidating和bool條件來檢查你是否調用.Validate()。
編輯
根據您最後的評論,爲什麼不爲dataGridView.IsCurrentRowDirty
添加一個檢查? 例如:
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e) {
if (dataGridView1.IsCurrentRowDirty) {
if (dataCheck())
if (MessageBox.Show("Ok?", "Save?", MessageBoxButtons.YesNoCancel) == DialogResult.Cancel) {
e.Cancel = true;
}
}
}
如果沒有髒數據,不管是誰調用dataCheck將不進行驗證,並在MessageBox將不會出現。
編輯
,可隨時更換「如果」條款與任何檢查要包括一個用於dataGridView2。
如果您有非常複雜的需求,也可以擴展dataGridView控件。
編輯
現在我明白你的要求。我不認爲有一個快速和乾淨的解決方案。我會使用SelectionChanged事件並設置邏輯來防止更改。例如:
//rember the selection of the index
private int _currentIndex;
private bool _rollingBackSelection;
private void SelectionChanged(...){
//when changing back to the selection in dgv1 prevent dgv2 check
if (_rollingBackSelection) {
_rollingBackSelection = false;
return;
}
if (dgv2IsDirty()) {
var result = MessageBox.Show("Ok?", "Save?", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Cancel) {
_rollingBackSelection = true;
//rollback to the previous index
dgv1.Rows[_currentIndex].Selected = true;
return;
}
if (result == DialogResult.Yes)
dgv2Save();
dgv2Load();
_currentIndex = dgv1.SelectedRows[0].Index;
}
}
我覺得上面的東西是你最好的拍攝。
,如果你不想讓用戶改變什麼用CellEndEdit?如果要防止用戶更改任何設置readonly = true – Ehsan
根據您希望防止某種輸入KeyPress事件設置Handled = true的情況,將阻止非法字符或字符格式。 - 另外,不區分不同的單元格,因此您必須測試正在編輯哪個列或行以進行正確的測試。 –
你可以擴展你想要達到的目標嗎? – CristisS