0

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

2 Answers 2

2

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"); } 
Sign up to request clarification or add additional context in comments.

1 Comment

The reason to use the Sender as TextBox pattern at the start there, is that you can make this a generic "decimal input validation" method. if you happen to have 5 text boxes on one page that all need 2 decimal point numeric validation, you can re-use this same method for all of them.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.