2016-06-27 29 views
0

離開細胞之前,我要檢查,如果用戶inputed號碼或一些其他字符,所以我使用的TryParse這裏是我的代碼:的TryParse同時CellValidating

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
    { 
     int n; 
     bool isNumeric = int.TryParse(dataGridView1.CurrentCell.FormattedValue.ToString(), out n); 
     if (isNumeric) 
     { 
      //Code 
     } 
     else 
     { 
      e.Cancel = true; 
     } 
    } 

在這兩種情況下,它給我的錯,不重要的是如果我輸入數字或任何其他字符。

+1

使用事件參數。那是他們的目標。你應該測試'e.Value' – Plutonix

+1

你應該考慮是否需要處理一個空單元:''「'。 – InBetween

+0

謝謝@Plutonix。 – Pacijent

回答

0

只需要與EventArgs的檢查當前單元格值,代碼如下所示:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    int n; 
    bool isNumeric = int.TryParse(e.FormattedValue.ToString(), out n); 
    if (isNumeric) 
    { 
     //Code 
    } 
    else 
    { 
     e.Cancel = true; 
    } 
}