DataGridView cell verification (only numbers are allowed)

Source: Internet
Author: User

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.

 

Related Article

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.