For example, only numbers are allowed.
Requirement: focus is not left after verification error
There are two methods:
The datagridview. editingcontrolshowing event and the datagridview. cellvalidating event.
(1) datagridview. editingcontrolshowing event.
When the control used to edit cells is displayed, the namespace is system. windows. forms.
Assembly: system. windows. forms (in system. windows. forms. dll ).
For example:
Void dgvcs_editingcontrolshowing (object sender, datagridvieweditingcontrolshowingeventargs e)
{
E. cellstyle. backcolor = color. aquamarine; // set the color during compilation.
Control = new textbox ();
Control = (textbox) e. control;
Control. keypress + = new keypresseventhandler (txt_keypress );//
}
Then verify it in txt_keypress.
(2) datagridview. cellvalidating event.
When the cell loses the input focus, content verification is enabled. Namespace: system. windows. form, assembly: system. windows. forms (in system. windows
. Forms. dll)
Note:
If the verification fails, call e. cancel = true to terminate the event chain. The cell remains editable.
Call dgv_details.canceledit (); the cell content can be rolled to the value before modification.
Use system. windows. forms. sendkeys. send ("^ a"); To select all cells.
For example:
Void dgv_cellvalidating (object sender, datagridviewcellvalidatingeventargs e)
{
Decimal tmp = 0.0 m;
If (! Decimal. tryparse (e. formattedvalue. tostring (), out tmp) // whether it is a number
{
If (e. formattedvalue! = Null & e. formattedvalue. tostring (). length! = 0)
{
Devcomponents. dotnetbar. messageboxex. show ("enter a valid number! "," Prompt ");
E. cancel = true;
}
}
}
Both methods can be verified. The first method is to verify when the key is pressed (that is, when compiling), and the second method is to trigger when the focus leaves the cell compilation area. Therefore, I personally feel that the first method is better.