In C #, datagridview implements that only numbers can be entered in a column.

Source: Internet
Author: User

 

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;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.