2016-12-05 41 views
0

我做了它的整數值,通過這個代碼,它的工作:DataGridView的細胞接受雙重價值只有

private void ItemsDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
    { 

     DataGridViewTextBoxCell cell =ItemsDataGridView[2, e.RowIndex] as DataGridViewTextBoxCell; 

     if (cell != null) 
     { 
      if (e.ColumnIndex == 2) 
      { 
       char[] chars = e.FormattedValue.ToString().ToCharArray(); 

       foreach (char c in chars) 
       { 
        if (char.IsDigit(c) == false) 
        { 
         MessageBox.Show("You have to enter digits only"); 

         e.Cancel = true; 
         break; 
        } 
       } 
      } 

我不想再拍細胞只接受雙重價值,以防止用戶輸入兩個點「 「。以避免錯誤

回答

0

保持簡單!

private void ItemsDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    if (e.ColumnIndex == 2) 
    { 
     double result; 

     if (!double.TryParse(e.FormattedValue.ToString(), out result)) 
     { 
      e.Cancel = true; 
     } 
    } 
} 

此外,使用替代MessageBoxErrorText屬性以指示用戶錯誤。

private void ItemsDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 
    if (e.ColumnIndex == 2) 
    { 
     double result; 

     if (!double.TryParse(e.FormattedValue.ToString(), out result)) 
     { 
      e.Cancel = true; 
      // Set error message 
      ItemsDataGridView.Rows[e.RowIndex].ErrorText = "You have to enter doubles only"; 
     } 
    } 
} 

private void ItemsDataGridView_CellValidated(object sender, DataGridViewCellEventArgs e) 
{ 
    // Clear error message 
    ItemsDataGridView.Rows[e.RowIndex].ErrorText = null; 
} 
+0

完美,謝謝 –