[英]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
}
}
For validation in windows control, please go through following articles 要在Windows控件中进行验证,请阅读以下文章
Validators for Windows Forms - ValidationProvider Control Windows窗体的验证器-ValidationProvider控件
User Input Validation in Windows Forms Windows表单中的用户输入验证
Using Error Provider Control in Windows Forms and C# 在Windows窗体和C#中使用错误提供程序控件
For web forms. 对于Web表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.