views:

87

answers:

3

Hi All,

I have several different controls (TextBoxes, DateTimePickers, MaskedTextBoxes) on a form that I would like to check to see if they contain any data. I have the following code in the Click event of my "Save" button:

    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!");
            }
        }
    }

This works fine for the TextBoxes and MaskedEditBoxes, however, it does not work for the DateTimePickers. For those, I know I need to check the .Value property, but I cannot seem to access that from the Control object (i.e. "control.Value == "" || control.Value == null").

Am I missing something obvious? Any suggestions of modifications I can make to this code to allow me to check the DateTimePicker values (or just to improve the code at all) will be greatly appreciated.

+2  A: 

You need to cast them to a DateTimePicker:

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

Also, use String.IsNullOrEmpty(control.Text) in the first part of your code.

BFree
A: 

You'll need to do something like this:

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, "");
        }
    }
}
John Fisher
A: 

There is no Value property for Controls; DateTimePicker, for example, creates its own property that is unique to it.

Unfortunately for you, there is no fully generic way of handling this from a single loop of Control objects. The best you can do is something along the lines of this:

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