Hoặc, đối với những người sử dụng KHÔNG muốn tạo DataGridView của riêng mình cho những dịp như vậy; có phương thức này (trong C++): Nó sử dụng sự kiện EditingControlShowing của DataGridView.
private: System::Boolean fIsNonNumeric;
private: static System::Windows::Forms::KeyEventHandler^ EventKeyDown = nullptr;
private: static System::Windows::Forms::KeyPressEventHandler^ EventKeyPress = nullptr;
private: System::Void dataGridView_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e)
{
fIsNonNumeric= false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e->KeyCode < Keys::D0 || e->KeyCode > Keys::D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e->KeyCode < Keys::NumPad0 || e->KeyCode > Keys::NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e->KeyCode != Keys::Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
fIsNonNumeric = true;
}
}
}
}
private: System::Void dataGridView_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e)
{
// Should we stop the character from being entered...?
if (fIsNonNumeric == true)
e->Handled = true;
}
private: System::Void dataGridView_Machines_EditingControlShowing(System::Object^ sender, System::Windows::Forms::DataGridViewEditingControlShowingEventArgs^ e)
{
if (nullptr == EventKeyDown)
EventKeyDown = (gcnew System::Windows::Forms::KeyEventHandler(this, &ProjectForm::dataGridView_KeyDown));
if (nullptr == EventKeyPress)
EventKeyPress = (gcnew System::Windows::Forms::KeyPressEventHandler(this, &ProjectForm::dataGridView_KeyPress));
e->Control->KeyDown -= EventKeyDown;
e->Control->KeyPress -= EventKeyPress;
e->Control->KeyDown += EventKeyDown;
e->Control->KeyPress += EventKeyPress;
}
Nguồn
2008-12-27 22:18:29
bạn có thể cung cấp thêm thông tin về cách làm như vậy không? – eladyanai