2009-08-25 2 views
0

데이터가 있는지 확인하려는 양식에 여러 가지 다른 컨트롤 (TextBoxes, DateTimePickers, MaskedTextBoxes)이 있습니다.데이터에 대한 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 작동하지 않습니다 : 내 "저장"버튼의 Click 이벤트에 다음 코드가 있습니다. 그 중, 나는 .Value 속성을 확인해야하지만 Control 객체 (즉, "control.Value ==" "|| control.Value == null")에서 액세스 할 수없는 것 같습니다.

나는 분명한 뭔가를 놓치고 있습니까? 이 코드를 수정하여 DateTimePicker 값을 확인하도록하거나 (또는 ​​코드를 개선하기 위해) 수정 제안을 해주시면 대단히 감사하겠습니다.

+0

도움 주셔서 감사합니다. 이제 제대로 작동하게되었습니다. – Sesame

답변

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

Control들에 대한 Value 재산이 없다; 예를 들어 DateTimePicker은 고유 한 고유 한 속성을 만듭니다.

불행히도 Control 개체의 단일 루프에서이를 처리하는 완전히 일반적인 방법은 없습니다. 최선의 방법은 다음과 같습니다.

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