saif beg

saif beg

  • NA
  • 31
  • 0

Keypress event for textbox

Aug 4 2011 8:07 AM
string str="";
        private void textBox31_KeyDown(object sender, KeyEventArgs e)
        {
          
   

            int KeyCode = e.KeyValue;

           

            if (!IsNumeric(KeyCode))
            {
                e.Handled = true;
                return;
            }
            else
            {
                e.Handled = true;
            }
            if (((KeyCode == 8) || (KeyCode == 46)) && (str.Length > 0))
            {
                str = str.Substring(0, str.Length - 1);
            }
            else if (!((KeyCode == 8) || (KeyCode == 46)))
            {
                str = str + Convert.ToChar(KeyCode);
            }
            if (str.Length == 0)
            {
                textBox31.Text = "0.00";
            }
            if (str.Length == 1)
            {
                textBox31.Text = "0.0" + str;
            }

            else if (str.Length == 2)
            {
                textBox31.Text = "0." + str;
            }
            else if (str.Length > 2)
            {
                textBox31.Text = str.Substring(0, str.Length - 2) + "." + str.Substring(str.Length - 2);
            }
        }
        private bool IsNumeric(int Val)
        {
            return ((Val >= 48 && Val <= 57)  || (Val == 8) || (Val == 46));
          
        }

        private void textBox31_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        
   

        }




I have used the above code for numeric precsion upto two.the problem is when i'm pressing number pad 0 to number 9 then number is not taking ..if i pressed the numbers above the qwerty keys in the keyboard then its taking.
please let me know where is the problem?

Answers (5)