2009-08-25 22 views
0

我在表單上有幾個不同的控件(TextBoxes,DateTimePickers,MaskedTextBoxes),我想檢查它們是否包含任何數據。我在我的「保存」按鈕的Click事件下面的代碼:檢查數據的Control.Value

private void radBtnSave_Click(object sender, EventArgs e) 
    { 
     this.Cancelled = false; 
     bool bValid = true; 

     foreach(Control control in this.Controls) 
     { 
      if (control.Tag == "Required") 
      { 
       if (control.Text == "" || control.Text == null) 
       { 
        errorProvider.SetError(control, "* Required Field"); 
        bValid = false; 
       } 
       else 
       { 
        errorProvider.SetError(control, ""); 
       } 
      } 
     } 

     if (bValid == true) 
     { 
      bool bSaved = A133.SaveData(); 
      if (bSaved != true) 
      { 
       MessageBox.Show("Error saving record"); 
      } 
      else 
      { 
       MessageBox.Show("Data saved successfully!"); 
      } 
     } 
    } 

也能正常工作的文本框和MaskedEditBoxes,但是,它不會爲DateTimePickers工作。對於那些,我知道我需要檢查.Value屬性,但我似乎無法從Control對象訪問它(即「control.Value ==」「|| control.Value == null」)。

我錯過了一些明顯的東西嗎?任何修改建議,我可以做這個代碼,讓我檢查DateTimePicker值(或只是爲了改善代碼)將不勝感激。

+0

謝謝大家的幫助!我現在正確地工作。 – Sesame 2009-08-26 14:58:41

回答

3

你需要將它們轉換成一個DateTimePicker:

DateTimePicker dtp = control as DateTimePicker; 
if(dtp !=null) 
{ 
    //here you can access dtp.Value; 
} 

而且,在你的代碼的第一部分使用String.IsNullOrEmpty(control.Text)。

0

你需要做這樣的事情:

foreach(Control control in this.Controls) 
{ 
    if (control.Tag == "Required") 
    { 
     DateTimePicker dtp = control as DateTimePicker; 
     if (dtp != null) 
     { 
      // use dtp properties. 
     } 
     else if (control.Text == "" || control.Text == null) 
     { 
      errorProvider.SetError(control, "* Required Field"); 
      bValid = false; 
     } 
     else 
     { 
      errorProvider.SetError(control, ""); 
     } 
    } 
} 
1

沒有Value屬性Control秒;例如,DateTimePicker創建了它自己的獨特屬性。

不幸的是,沒有完全通用的方式來處理來自單個循環的Control對象。你可以做的最好的是沿着這條線:

if(control is DateTimePicker) 
{ 
    var picker = control as DateTimePicker; 
    // handle DateTimePicker specific validation. 
}