开发者

c# how to check if a text box has one digit?

at the moment, my program crashes if only one digit exists inside a textbox. E.g. User puts '6' into a Day textbox (which it should be two digits), and the program will crash when he/she clicks the 'Convert' button. It has to be two digits or else the program crashes...

my application is a time converter, by the way.

thank开发者_Go百科s in advance :)


It has to be two digits or else the program crashes

This is a bug, fix your program. It’s extremely bad manners to make the user conform to some arbitrary format when the program could equally be made understand another format.

There is no reason why entering one digit instead of two should result in an error.


If you want to parse dates, you can use DateTime.TryParse. Here are a couple of other approaches:

  • Check the length of each textbox ( not culture friendly )
  • Override textbox and create your own sub-class which overrides the On Key Pressed-event so that you can decide what you want to allow or not.


You check it like this:

if (TheDayTextbox.Text.Length != 2) {
  // illegal length
}

Of course, you could fix it if it's shorter:

string day = TheDayTextbox.Text;
if (day.Length == 1) {
  day = "0" + day;
}


Assuming this is a web app - you can get the value of textbox in javascript variable and then check the length using "length" property in javascript.


This is what we call VALIDATION and it's a very important stuff.

You should never write code that assumes anything at all, validate it first!

for example:

if( myTextBox.Text.Length > 1 ) {

    // continue the process

} else {

    MsgBox.Show("Can you please do things right for once?");
}

will do the trick you want, but there are already Validators on .NET Framework that you could take advantage of.

tell us if it's windows or web and we will help you out on the Validation part.


If you are talking about WinForms then you can just check against textBox.Text.Length

if(textBox1.Text.Length <= 1)
{
   // handle error
}


    int res = -1;

    if(textBox.Text.Length == 2) {
      Int32.tryParse(textBox.Text, res)
    }


    if(res > 0) {
   //   convert
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜