tags:

views:

129

answers:

3

hi guys, I am using following code for validating textbox.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = SingleDecimal(sender, e.KeyChar);
        }



   public bool SingleDecimal(System.Object sender, char eChar)
    {

       string chkstr = "0123456789.";

        if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack) {

            if (eChar == ".") {

              if (((TextBox)sender).Text.IndexOf(eChar) > -1) {


                 return true;
              }
               else {


                  return false;

               }
          }

           return false;
       }
      else {


           return true;

       }
   }

Problem is Constants.vbBack is showing error.If i didnt use Constants.vbBack,backspace is not workimg.What alteration can i make to work backspace.Can anybody help?

A: 

Here some code from my app. It handle one more case as will related to selection

protected override void OnKeyPress(KeyPressEventArgs e)
{
    if (e.KeyChar == '\b')
        return;
    string newStr;
    if (SelectionLength > 0)
        newStr = Text.Remove(SelectionStart, SelectionLength);

    newStr = Text.Insert(SelectionStart, new string(e.KeyChar, 1));
    double v;
   //I used regular expression but you can use following.
    e.Handled = !double.TryParse(newStr,out v);

    base.OnKeyPress(e);
}

here regex expression if like to use them instead of that easy type parsing

const string SIGNED_FLOAT_KEY_REGX = @"^[+-]?[0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]*)?$";
const string SIGNED_INTEGER_KEY_REGX = @"^[+-]?[0-9]*$";

const string SIGNED_FLOAT_REGX = @"^[+-]?[0-9]*(\.[0-9]+)?([Ee][+-]?[0-9]+)?$";
const string SIGNED_INTEGER_REGX = @"^[+-]?[0-9]+$";
affan
A: 

How about using the example from MSDN?

Are u using the '.' as decimal seperator? if so than I don't know why you are using

if (((TextBox)sender).Text.IndexOf(eChar) > -1)
PoweRoy
+1  A: 

here is the code I would use...

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        // allows 0-9, backspace, and decimal
        if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
        {
            e.Handled = true;
            return;
        }

        // checks to make sure only 1 decimal is allowed
        if (e.KeyChar == 46)
        {
            if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
                e.Handled = true;
        }
    }
Eclipsed4utoo