2011-04-16 75 views

回答

4

我知道有兩種方法可以用於此目的。第一個(我認爲最好的)是使用DataGridView上的CellValidating事件並檢查輸入的文本是否是數字。

下面是一個設置行錯誤值的例子(使用額外的CellEndEdit事件處理程序來防止用戶取消編輯)。

private void dataGridView1_CellValidating(object sender, 
     DataGridViewCellValidatingEventArgs e) 
    { 
     string headerText = 
      dataGridView1.Columns[e.ColumnIndex].HeaderText; 

     // Abort validation if cell is not in the Age column. 
     if (!headerText.Equals("Age")) return; 

     int output; 

     // Confirm that the cell is an integer. 
     if (!int.TryParse(e.FormattedValue.ToString(), out output)) 
     { 
      dataGridView1.Rows[e.RowIndex].ErrorText = 
       "Age must be numeric"; 
      e.Cancel = true; 
     } 

    } 

    void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
    { 
     // Clear the row error in case the user presses ESC. 
     dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty; 
    } 

第二種方法是使用EditingControlShowing事件和事件附着到細胞的按鍵響應 - 我不是這種方法的這樣的粉絲,因爲非數字鍵,它靜靜地阻擋輸入 - 雖然我猜想你可以給出一些反饋(比如響亮的鈴聲),與其他方式相比,它只是感覺更多的工作。

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    e.Control.KeyPress -= TextboxNumeric_KeyPress; 
    if ((int)(((System.Windows.Forms.DataGridView)(sender)).CurrentCell.ColumnIndex) == 1) 
    { 
     e.Control.KeyPress += TextboxNumeric_KeyPress; 
    } 
} 

private void TextboxNumeric_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    bool nonNumberEntered = true; 

    if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8) 
    { 
     nonNumberEntered = false; 
    } 

    if (nonNumberEntered) 
    { 
     // Stop the character from being entered into the control since it is non-numerical. 
     e.Handled = true; 
    } 
    else 
    { 
     e.Handled = false; 
    } 
} 

與此相關的一個重要注意事項是小心刪除編輯控件中顯示方法的控件上的事件處理程序。這是很重要的,因爲DataGridView爲同一類型的每個單元重複使用同一個對象,包括跨不同的列。如果您將事件處理程序附加到一個文本框列中的控件,則網格中的所有其他文本框單元格將具有相同的處理程序!此外,還會附加多個處理程序,每次顯示控件時都會有一個處理程序。

第一個解決方案來自this MSDN article。第二個來自this blog

+0

乾杯,隊友!!!! – Bahman 2011-04-17 09:32:29

+0

第二種解決方案有兩個問題。首先是一旦Keypress事件在第一列中被替換,它對所有列都有效。第二個是它鏈接到自身,這樣每次在第一列中按下一個鍵時,處理程序會再次被添加。所以每個按鍵事件都會發生多次。 – 2012-12-08 03:43:13

+0

@RichShealer謝謝,通過首先刪除事件來解決這個問題。正如我所說的,在這種情況下,這並不是我的首選方法。 – 2012-12-08 11:47:40

0

如果您希望datagridview只是爲用戶刪除無效字符,而不是發出錯誤消息,請使用DataGridView.CellParsing()。此事件僅在您進行單元格編輯後觸發,並允許您覆蓋輸入的內容。

例如:

private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e) 
{ 
    // If this is column 1 
    if (e.ColumnIndex == 1) 
    { 
     // Remove special chars from cell value 
     e.Value = RemoveSpecialCharacters(e.Value.ToString()); 
     e.ParsingApplied = true; 
    } 
} 

對於RemoveSpecialCharacters()方法,見this SO question用於從字符串中除去特殊字符的一些優秀的方法。

+0

使用** EditingControlShowing **事件而不是** CellParsing **請參閱[link](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.editingcontrolshowing(v = vs。 110)的.aspx) – 2017-08-03 03:29:21

相關問題