I'm new about C#, I learnt C programmation for one year now.
I created a Window Form which asks the user to complete a registration form.
I'd like to display an error message below the buttons when a field is not filled or a field isn't well used.
I used this basic code :
private void button1_Click(object sender, EventArgs e)
{
if (!isOkay(userTextBox.Text))
{
label5.Text = "Please, enter an username.";
label5.Visible = true;
}
else if (!isOkay(mailTextBox.Text))
{
label5.Text = "Please, enter a mail address.";
label5.Visible = true;
}
else if (!confirmMailTextBox.Text.Equals(mailTextBox.Text) || !isOkay(confirmMailTextBox.Text))
{
label5.Text = "Please, match both mails addresses.";
label5.Visible = true;
}
else if (!isOkay(passwordTextBox.Text))
{
label5.Text = "Please, enter a password.";
label5.Visible = true;
}
else
{
label5.Text = "Valid form, yay !";
label5.Visible = true;
}
}
private Boolean isOkay(string textBoxContent)
{
return (textBoxContent.Length > 0 || textBoxContent.Equals(null));
}
Are there any elegant or optimized ways to do it properly ? I found some Error providers, but apparently error providers open a pop-up, and I just want a "red error message below buttons".
Can you give me some help ? :)
Given a class like this
then you could change your code to
This approach avoids the unnerving situation (for your user) when he/she receives an error message, he/she fixes it just to receive another error message at the next attempt to confirm the form.
Of course your label should be tall enough to show all the possible messages or just use a messagebox.
I suggest also to change your
IsOkay
function tothis will handle also a string composed just of one or more spaces. (not null and not length==0)
You can use ErrorProvider. It show's an error icon after your textbox.
For one of your textboxes for example:
Link: http://www.dotnetperls.com/errorprovider