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
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);
// 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;
}
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.
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
精彩评论