TextBox Validation in Visual Studio C#

2019-09-11 02:13发布

问题:

I am fairly new to Visual Studio and C# in general but basically I need to check that the contents of the textbox are valid before proceeding to add the contents to a list with a button.

I am using the following objects: A TexBox to enter the value A Validating event linked to the TextBox to validate the data. A Button to take action A Click event associated to the button.

The problem is that I cannot check if the values in the box are valid or not and prevent the click event in the button to happen. In other words if the contents are not valid then do not take action.

This is my code.

public partial class mainForm : Form
{
    public mainForm()
    {
        InitializeComponent();
    }

    private void addButton_Click(object sender, EventArgs e)
    {
        // I need to check if the content is valid before adding it to the form
        ListViewItem item = new ListViewItem(this.nameTextBox.Text);
        this.listView1.Items.Add(item);
    }

    private void nameTextBox_Validating(object sender, CancelEventArgs e)
    {
        int maxCharacters = 15;
        String err = "";
        String contents = this.nameTextBox.Text;

        if (contents.Length == 0)
        {
            err = "I am sorry but the name cannot be empty";
            e.Cancel = true;
        }
        else if (!contents.Replace(" ", "").Equals(contents, StringComparison.OrdinalIgnoreCase))
        {
            err = "I am sorry but the name cannot contain spaces";
            e.Cancel = true;
        }
        else if (contents.Length > 15)
        {
            err = "I am sorry, but the name cannot have more than " + maxCharacters + " characters";
            e.Cancel = true;
        }

        this.mainFormErrorProvider.SetError(this.nameTextBox, err);
    }
}

回答1:

You are confused about when the "name" text boxes' validation method is called.

See here

When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Selector SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order...

So clicking the button has nothing to do with the validation of the text box.

What you need to do is put the validation logic in a separate method, and then call it from both events.

Also, since you're new to C# here are some pointers.

Namespaces, Classes, methods, and properties are supposed to be Pascal Case.

Instead of using a long winded work around like this

!contents.Replace(" ", "").Equals(nameText, StringComparison.OrdinalIgnoreCase)

You could simply use

contents.Contains(" ")

There are tons of useful methods just like that, so in the future you should do more research on what you need before implementing something yourself, especially if it seems like a commonly used technique.

Also, you want to avoid if/else's as much as possible in favour of returning early.

Here's what your class might look with better practice in mind

const int NAME_MAX_CHARACTERS = 15;

public mainForm()
{
    InitializeComponent();
}

private void addButton_Click(object sender, EventArgs e)
{
    if(!Validate())
    {
        return;
    }

    // I need to check if the content is valid before adding it to the form
    ListViewItem item = new ListViewItem(this.nameTextBox.Text);
    this.listView1.Items.Add(item);
}

private void nameTextBox_Validating(object sender, CancelEventArgs e)
{
    e.Cancel = !Validate();
}

private bool Validate()
{
    string nameText = nameTextBox.Text;

    if(String.IsNullOrEmpty(nameText))
    {
        this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry but the name cannot be empty");
        return false;
    }

    if(nameText.Contains(" "))
    {
        this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry but the name cannot contain spaces");
        return false;
    }

    if (nameText.Length > 15)
    {
        this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry, but the name cannot have more than " + NAME_MAX_CHARACTERS + " characters");
        return false;
    }

    return true;
}