简体   繁体   English

Visual Studio C#中的文本框验证

[英]TextBox Validation in Visual Studio C#

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. 一般而言,我对Visual Studio和C#还是相当陌生,但是基本上我需要先检查文本框的内容是否有效,然后再将内容添加到带有按钮的列表中。

I am using the following objects: A TexBox to enter the value A Validating event linked to the TextBox to validate the data. 我正在使用以下对象:一个TexBox输入值一个Validating事件链接到TextBox以验证数据。 A Button to take action A Click event associated to the button. 采取措施的按钮与该按钮关联的Click事件。

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);
    }
}

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... 当您使用键盘(TAB,SHIFT + TAB等),通过调用Selector SelectNextControl方法或将ContainerControl.ActiveControl属性设置为当前窗体来更改焦点时,焦点事件将按以下顺序发生。 。

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. 另外,由于您不熟悉C#,因此这里有一些指针。

Namespaces, Classes, methods, and properties are supposed to be Pascal Case . 命名空间,类,方法和属性应该是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. 另外,您也希望尽可能避免if / else,而希望早日返回。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM