Reprint: http://www.cnblogs.com/ganqiyin/archive/2013/02/18/2915491.html
Event: DataGridView verifies that the cell entered is a number, DataGridView the source data is read from the database.
Requirements: When the user input is not the number of the need to prompt information (the data is directly bound to the database, so DataGridView has its own error function, we need to block it out, show their own error prompt!) )
Implementation: Select DataGridView's Cellvalidating Event
(1) Verifying integers:
View Code
1Privatevoid Gridplant_cellvalidating (Objectsender, Datagridviewcellvalidatingeventargs e)2{3if (E.rowindex >-1 && e.columnindex >-1)4{5 DataGridView Grid =(DataGridView) sender;6 grid. Rows[e.rowindex]. ErrorText ="";7//It's best to use column names instead of column index numbers to make judgments.8if (grid. Columns[e.columnindex]. Name = ="Wo0011_number_idle" || Grid. Columns[e.columnindex]. Name = ="Wo0011_number_working" || Grid. Columns[e.columnindex]. Name = ="Wo0011_number_on_site")9{10Int32 Newinteger =0;12if (!Int. TryParse (E.formattedvalue.tostring (),OutNewinteger))13{E.cancel =true; Grid. Rows[e.rowindex]. ErrorText = "please Enter a int number! "; 16 MessageBox.Show ( The value is not nubmer, pleaser enter a int number! "); 17 return;18 }19 }20 }21}
(2) Verify the decimal number:
View Code
1Privatevoid Gridbriefsolder_cellvalidating (Objectsender, Datagridviewcellvalidatingeventargs e)2{3if (E.rowindex >-1 && e.columnindex >-1)4{5 DataGridView Grid =(DataGridView) sender;6 grid. Rows[e.rowindex]. ErrorText ="";78if (grid. Columns[e.columnindex]. Name = ="Wo0009_approximate_completion_percentage1")9{10Try11{12Convert.todecimal (E.formattedvalue);13}14Catch15{E.cancel =true; Grid. Rows[e.rowindex]. ErrorText = "please Enter a number! "; 18 MessageBox.Show ( The value is not nubmer, pleaser enter a number! "); 19 return;20 }21 }22 }23}
= = does not set CausesValidation, then an infinite loop appears in the Cellvalidating in DataGridView.
This.dgvRecyclePackage.CausesValidation = false;
That's all you can do.
WinForm DataGridView Validation Cell input is a number