2012-10-14 41 views
0

嗨,GUI讓用戶輸入幾種不同類型的數據。我如何去驗證用戶輸入,使它不是空白,並且有些值檢查它是否在一個數字範圍內?如何使用按鈕驗證c#中文本框的內容?

+0

您使用的是哪種UI技術? ASP.Net?的WinForms? WPF?.. GTK#?我們需要知道...... – Darbio

+0

您需要的是大量的「if ... {}」語句。如果使用ASP.NET,你會在客戶端使用JavaScript來創建一些漂亮的插件。 –

+0

我正在使用C#.Net窗體 – user1743574

回答

0

對於非空值,您只需檢查string.IsNullOrWhiteSpace(value)是否返回true或false。

對於整數範圍檢查,如果value<=100 && value>=0

對於日期,檢查是否DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed)是真還是假

0

您可以創建IsValid(或像這樣)方法您Student類中(我假設student1Student類的對象):

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

嘿,這很好,但是我怎麼會爲日期和範圍做呢? – user1743574

+0

@ user174357朋友,請閱讀一些教程。因爲明天之後你會有更多的條件來驗證。如果你明白基本,你可以處理所有這些。 –

+0

乾杯,將做 – user1743574