Recently, when developing a project, only a number can be entered in a column. Other characters are not accepted. Microsoft does not provide this function and can only implement it by code, I found it online. Most of them are verified only after the input is complete. In this way, the Code shields non-numeric characters from input. It is mainly completed in the editingcontrolshowing event. Check the Code:
Public datagridviewtextboxeditingcontrol celledit = NULL; // declare a celledit
Private void datagridyf_editingcontrolshowing (Object sender, datagridvieweditingcontrolshowingeventargs E)
{
Celledit = (datagridviewtextboxeditingcontrol) E. Control; // The value celledit. selectall ();
Celledit. keypress + = cells_keypress; // bind to event
}
// Custom event
Private void cells_keypress (Object sender, keypresseventargs E)
{
If (datagridyf. currentcelladdress. x = 2) // determines whether the current column is the column to be controlled. I am the column whose index value is 2 (that is, the third column)
{
If (convert. toint32 (E. keychar) <48 | convert. toint32 (E. keychar)> 57) & convert. toint32 (E. keychar )! = 46 & convert. toint32 (E. keychar )! = 8 & convert. toint32 (E. keychar )! = 13)
{
E. Handled = true; // block an invalid input.
}
Else
{
If (convert. toint32 (E. keychar) = 46) & (txtjg. Text. indexof (".")! =-1 ))
{
E. Handled = true;
}
}
}
}
The verification is completed only after the input is complete. This is mainly done in the cellvalidating event.
Private void datagridyf_cellvalidating (Object sender, datagridviewcellvalidatingeventargs E)
{If (E. columnindex = datagridyf. Columns ["pric"]. Index)
{
Datagridyf. Rows [E. rowindex]. errortext = "";
Int newval = 0;
If (! Int. tryparse (E. formattedvalue. tostring (), Out newval) | newval <0)
{
E. Cancel = true;
Datagridyf. Rows [E. rowindex]. errortext = "only numbers can be entered in the price column ";
Return;
}
}
}