1

I am working in C#, Windows Form Application.

I have 6 text boxes that accept user input. When the 'Submit' button is clicked it stores the values in an array. I want to create something to check the text boxes for two things 1.) there is something in the text boxes and 2.) the information is only a number, nothing else.

I have been told that a try catch loop will be able to do this, but I have yet to figure out how.

Thank you for any help you can provide

Matt
  • 11
  • 1
  • 2

4 Answers4

3

You do not want to use a try catch block for this - you should not use exceptions for standard application flow as it is a relatively expensive option.

Checking if it is empty

string.IsNullOrEmpty(textbox1.Text);

Checking if it is a number

int result;
int.TryParse(textbox1.Text), out result);
Peter Kelly
  • 13,347
  • 6
  • 51
  • 62
1
// In button_click event or somewhere like that

if (!this.CheckInput(txt_TextBox1))
    return;

if (!this.CheckInput(txt_TextBox2))
    return;

if (!this.CheckInput(txt_TextBox3))
    return;

// Everything OK, do something

Then a method like this:

private bool CheckInput(TextBox textbox) {

    int test;

    if (!int.TryParse(textbox.Text.Trim(), out test)) {
        MessageBox.Show("Invalid input");
        return false;
    }

    return true;
}
kprobst
  • 14,949
  • 5
  • 29
  • 52
1

To check if something is in the textbox you can call the string.IsNullOrEmpty method.

As for checking if a Textbox only contains numeric values, you might want to consider preventing users from entering non-numeric values. This would be a more user friendly approach than preventing it after entering the values.

Bas
  • 25,270
  • 7
  • 45
  • 82
1

You can use isNullOrEmtpy as Bas suggested above in order to check if there is any user input. For numeric numbers only, i suggest you use Regex. You can find a solution here

Community
  • 1
  • 1
Yagiz Ozturk
  • 5,208
  • 7
  • 26
  • 43