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

时间:2012-10-14 11:04:06

标签: c# winforms validation

用户界面可以输入几种不同类型的数据。如何验证用户输入以使其不是空白,并检查某些值是否在一个数字范围内?

3 个答案:

答案 0 :(得分:0)

对于非空值,您只需要检查string.IsNullOrWhiteSpace(value)是返回true还是false。

对于整数范围,请检查value<=100 && value>=0

对于日期,请检查DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed)是真还是假

答案 1 :(得分:0)

您可以在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;
    }
}

以后:

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

答案 2 :(得分:0)

相关问题