[英]How do I validate the contents of a textbox in c# with a button?
嗨,一個GUI,允許用戶輸入幾種不同類型的數據。 我該如何驗證用戶輸入,以使其不為空白,並檢查某些值是否在數字范圍內?
對於非空白值,您只需要檢查string.IsNullOrWhiteSpace(value)
返回true還是false。
對於整數范圍,請檢查value<=100 && value>=0
對於日期,請檢查DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed)
是true還是false
您可以創建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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.