简体   繁体   English

如何使用按钮验证c#中文本框的内容?

[英]How do I validate the contents of a textbox in c# with a button?

Hi a GUI that lets the user input a few different types of data. 嗨,一个GUI,允许用户输入几种不同类型的数据。 How do I go about validating the user input so that it is not blank and for some values to check if it is within a range of numbers? 我该如何验证用户输入,以使其不为空白,并检查某些值是否在数字范围内?

For not blank values, you merely need to check whether string.IsNullOrWhiteSpace(value) returns true or false. 对于非空白值,您只需要检查string.IsNullOrWhiteSpace(value)返回true还是false。

For an integer range check if value<=100 && value>=0 对于整数范围,请检查value<=100 && value>=0

For the date, check if DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed) is true or false 对于日期,请检查DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed)是true还是false

You can create IsValid (or something like this) method inside your Student class (I assume that student1 is object of class Student ): 您可以创建IsValid (或像这样)你的方法里面Student类(我认为student1是类的对象Student ):

class Student
{
    // your code
    // ...
    public bool IsValid()
    {
        bool isValid = true;

        if(string.IsNullOrWhiteSpace(FirstName))
        {
           isValid = false;
        }
        else if(string.IsNullOrWhiteSpace(LastName))
        {
           isValid = false;
        }
        // ... rest of your validation here

        return isValid;
    }
}

and later: 然后:

private void button1_Click(object sender, EventArgs e)
{
    student1.FirstName = firstnamebox.Text;
    student1.SecondName = secondnamebox.Text;
    student1.DateofBirth = DateTime.Parse(dobtextbox.Text).Date;
    student1.Course = coursetextbox.Text;
    student1.MatriculationNumber = int.Parse(matriculationtextbox.Text);
    student1.YearMark = double.Parse(yearmarktextbox.Text);

    if(student1.IsValid())
    {
        // good
    }
    else
    {
        // bad
    }
}

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

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