Click here to Skip to main content
16,022,542 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I created Codes for Validating Textbox Correct to 2 decimal Places using the code given below.

C#
private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
        {
            string str = txtAge.Text;                               //  User Control
            int len = str.Length;
            int index = 0;
            int dcml = 2;                                           // 2 indeicates the Deccimal Points Needed   (User Defined)
            if (str.Contains('.'))
            {
                index = str.IndexOf('.');
                index = len - index;
            }
            if (Char.IsControl(e.KeyChar) == false)
            {
                if (((Char.IsDigit(e.KeyChar)) && (index <= dcml)) || ((e.KeyChar == '.') && (!(str.Contains('.')))))
                {
                }
                else
                {
                    e.Handled = true;
                }
            }
        }



but I cannot use this code to Correct the Text Validation in Data Grid View, string str is not taking the value from datagridview cell. it gets only the null values. but It accepts only digits and decimal points. I can enter any number of decimal points and any numbers after decimal point. How can i change this, restricting the value to 2 decimal places and allow only one decimal point.
Posted

1 solution

All wrong. Do not store strings in cells, store numeric data. Just control the way it is formatted using the event System.Windows.Forms.DataGridView.CellFormatting. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900