2017-07-04 45 views
0

我有一個網格視圖包含多個列,我將其輸入類型調整爲doubleDataGridView如何驗證和選擇單元格

當用戶選擇一個單元格時,輸入其數據,我想檢查它是否與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"); 
       } 
      } 
     } 

回答

1

您可以使用事件DataGridView.CellValidating。這應該可以解決你的問題。

例子:

private void dataGridView1_CellValidating(object sender, 
              DataGridViewCellValidatingEventArgs e) 
    { 
     if (e.ColumnIndex == 1) // 1 should be your column index 
     { 
      int i; 

      if (!int.TryParse(Convert.ToString(e.FormattedValue), out i)) 
      { 
       e.Cancel = true; 
       label1.Text ="please enter numeric"; 
      } 
      else 
      { 
       // the input is numeric 
      } 
     } 
    } 

DataGridView.CellValidating Event

How to: Validate Data in the Windows Forms DataGridView Control

CellValueChanged vs CellValidating Events for DataGridView

+0

你有沒有嘗試它和它的作品?請爲我提供一個示例代碼,因爲我嘗試了它,但它不適用於我。 –

+0

是的,它像魅力一樣工作。 Dgv「CellValidating」,當你打算離開實際的細胞時(或者點擊其他細胞,或者按下回車鍵),就會上升。 – krzysztofla

+0

謝謝!當我使用CellValidating時,我只需要添加這行'e.Cancel = true;'。現在它完美地工作。 –

相關問題