2010-04-16 51 views
0

看來,捕獲DataGridView控件的單元格中按鍵事件的唯一方法是在使用DataGridView控件的OnEditControlShowing事件時,將編輯控件的方法(例如,控制)按鍵事件並做一些驗證。如何驗證DataGridView中單元格的編輯控件的輸入?

我的問題是,我已經建立了一堆自定義的DataGridView列類,他們自己的自定義單元格類型。這些單元格有自己的自定義編輯控件(如DateTimePickers和數字或貨幣文本框的東西)。

我想爲那些具有貨幣文本框的數字作爲其編輯控件但不是所有其他單元格類型的單元格進行一些數字驗證。

如何確定在DataGridView的「OnEditControlShowing」覆蓋中,某個特定編輯控件是否需要某些數字驗證?

回答

1

如果我正確理解你的問題,你想選擇基於類型的編輯控件來連接事件。如果是這樣,這是我會怎麼做:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     //Remove any KeyPress events already attached 
     e.Control.KeyPress -= new KeyPressEventHandler(FirstEditingControl_KeyPress); 
     e.Control.KeyPress -= new KeyPressEventHandler(SecondEditingControl_KeyPress); 

     //Choose event to wire based on control type 
     if (e.Control is NumericTextBox) 
     { 
      e.Control.KeyPress += new KeyPressEventHandler(FirstEditingControl_KeyPress); 
     } else if (e.Control is CurrencyTextBox) 
     { 
      e.Control.KeyPress += new KeyPressEventHandler(SecondEditingControl_KeyPress); 
     } 
    } 

我從經驗中學到的無線化DataGridView的對編輯控制任何可能的事件,因爲它們會重用多個單元相同的控制。

+0

我也這麼認爲,但似乎編輯控件總是類型DataGridViewTextBoxEditingControl? – 2010-04-17 05:59:09

相關問題