panjo
panjo

Reputation: 3515

accept and validate decimal input in winforms

Inside form I want to add txtbox which should accept inputs as decimals with 2 decimals or without decimals, if user enters just 1 at the db level decimals would be added, and if user enters 1.00 even better.

I'm new to winforms and I need advice (steps to complete) for described situation and validation of user input, accept only numbers with possible . (dot) beetween digits.

I don't need heavy approach since I would have only 2 forms so simple, concrete example would be ok.

Thanks

Upvotes: 0

Views: 2988

Answers (2)

Alyafey
Alyafey

Reputation: 1453

You can do this:

First you can use a button to validate

private void btnValdiate_Click(object sender, EventArgs e)
    {           
        decimal value;

        if(Decimal.TryParse(textBox1.Text,out value))
        {
            bool check = TwoDecimalPlaces(value);
             if(check )
              {
               //do something 
              }else
              {
               //do something else
               }
        }else
        {
          // do something 
        }
    }
    private bool TwoDecimalPlaces(decimal dec)
    {
        decimal value = dec * 100;
        return value == Math.Floor(value);
    }

Second you can do it by using TextChanged event such as:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            decimal value;

            if(Decimal.TryParse(textBox1.Text,out value))
            {
                bool check = TwoDecimalPlaces(value);
                 if(check )
                  {
                   //do something 
                  }else
                  {
                   //do something else
                   }
            }else
            {
              // do something 
            }
        }
 private bool TwoDecimalPlaces(decimal dec)
        {
            decimal value = dec * 100;
            return value == Math.Floor(value);
        }

or you can also use Regex take a look at:

http://regexlib.com/DisplayPatterns.aspx?cattabindex=2&categoryId=3&AspxAutoDetectCookieSupport=1

Upvotes: 1

Nevyn
Nevyn

Reputation: 2683

you should look into FormatStrings

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

How I would do this with a WinForms object is to implement the Validating event and use this not only for input validation, to make certain that the user did in fact enter a number, but also to reformat their input.

private void textBox1_Validating (object Sender, CancelEventArgs e)
{
    TextBox tx = Sender as TextBox;
    double test;
    if(!Double.TryParse(tx.Text, out test))
    { 
        /* do Failure things */ 
    }
    else //this is the formatting line
        tx.Text = test.ToString("#,##0.00");
}

Upvotes: 2

Related Questions