0

我在一个表单上有几个不同的控件(TextBoxes、DateTimePickers、MaskedTextBoxes),我想检查它们是否包含任何数据。我的“保存”按钮的 Click 事件中有以下代码:

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

这适用于 TextBoxes 和 MaskedEditBoxes,但是,它不适用于 DateTimePickers。对于那些,我知道我需要检查 .Value 属性,但我似乎无法从 Control 对象访问它(即“control.Value ==”“|| control.Value == null”)。

我错过了一些明显的东西吗?我可以对此代码进行修改以允许我检查 DateTimePicker 值(或只是为了改进代码)的任何建议将不胜感激。

4

3 回答 3

3

您需要将它们转换为 DateTimePicker:

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

此外,在代码的第一部分使用 String.IsNullOrEmpty(control.Text)。

于 2009-08-25T21:24:35.657 回答
1

s没有Value属性ControlDateTimePicker例如,创建自己独有的属性。

对您来说不幸的是,没有完全通用的方法可以从单个Control对象循环中处理此问题。你能做的最好的事情是这样的:

if(control is DateTimePicker)
{
   var picker = control as DateTimePicker;
   // handle DateTimePicker specific validation. 
}
于 2009-08-25T21:26:34.483 回答
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, "");
        }
    }
}
于 2009-08-25T21:25:34.797 回答