0
我有一個網格視圖包含多個列,我將其輸入類型調整爲double
。DataGridView如何驗證和選擇單元格
當用戶選擇一個單元格時,輸入其數據,我想檢查它是否與double
的類型匹配。
如果用戶點擊另一個單元格,並且他將要離開的單元格不匹配,並且解析失敗,我希望焦點返回到失敗的單元格,而不是移動到新選定的單元格以強制用戶在繼續填充其餘單元格之前輸入有效數據。
問題是它總是離開失敗的單元。即使當我使用其他函數,如驗證或驗證。
這裏是我的代碼示例:
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
var selectedCell = dataGridView1.SelectedCells[0];
if (selectedCell.OwningColumn.ValueType == typeof(double))
{
try
{
double result = Convert.ToDouble(selectedCell.EditedFormattedValue.ToString());
if (result <= 0)
{
MessageBox.Show("Please Positive Numbers Only");
dataGridView1.Focus();
dataGridView1.CurrentCell = dataGridView1.Rows[selectedCell.RowIndex].Cells[selectedCell.ColumnIndex];
dataGridView1.BeginEdit(true);
}
else
{
dataGridView1.CurrentCell.Value = result;
}
}
catch
{
MessageBox.Show("Please Enter Numbers Only");
}
}
}
你有沒有嘗試它和它的作品?請爲我提供一個示例代碼,因爲我嘗試了它,但它不適用於我。 –
是的,它像魅力一樣工作。 Dgv「CellValidating」,當你打算離開實際的細胞時(或者點擊其他細胞,或者按下回車鍵),就會上升。 – krzysztofla
謝謝!當我使用CellValidating時,我只需要添加這行'e.Cancel = true;'。現在它完美地工作。 –