如何在外部类的许多表单上将所有DatePicker更改为自定义格式

时间:2016-07-07 16:36:48

标签: c# winforms

我有这种方法可以从一种形式更改所有DatePicker的格式:

public void FormatDateTimePickers()
        {
            foreach (Control c in this.Controls)
            {
                var dateTimePicker = c as DateTimePicker;

                if (dateTimePicker != null)
                {
                    dateTimePicker.Format = DateTimePickerFormat.Custom;
                    dateTimePicker.CustomFormat = "dd/MM/yyyy";
                }
            }
        }

但我的继承形式太多了。例如:

class frm1:Form

class frm2:Form

class frm3:Form

每个类都有特定的参数。

我想创建另一个类,使用方法更改DateTimePickers格式,并在每个表单类上调用它。

所以,我试过了:

clsWinFormsGeneric.cls:

public partial class clsWinFormsGeneric : Form
    {
        public void FormatDateTimePickers(object customform)
        {
            foreach (Control c in customform.Controls)
            {
                var dateTimePicker = c as DateTimePicker;

                if (dateTimePicker != null)
                {
                    dateTimePicker.Format = DateTimePickerFormat.Custom;
                    dateTimePicker.CustomFormat = "dd/MM/yyyy";
                }
            }
        }
    }

并在frm1.class中:

clsWinFormsGeneric.FormatDateTimePickers(this);

但我收到错误:对象没有Controls属性。

我能做什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

对于您的代码,只需将参数从object更改为From:

public void FormatDateTimePickers(Form customform)
{
    foreach (Control c in customform.Controls)
    {
        var dateTimePicker = c as DateTimePicker;

        if (dateTimePicker != null)
        {
            dateTimePicker.Format = DateTimePickerFormat.Custom;
            dateTimePicker.CustomFormat = "dd/MM/yyyy";
        }
    }
}

我建议你做另一种方法:

对我来说,直接的解决方案是创建一个只包含DatePicker的使用控件,并在构造函数中设置格式。

public partial class CustomDatePicker : UserControl
{
    public CustomDatePicker()
    {
        InitializeComponent();

        dateTimePicker.Format = DateTimePickerFormat.Custom;
        dateTimePicker.CustomFormat = "dd/MM/yyyy";
    }
}

我不喜欢的另一种方法是使用你所形成的所有BaseForm继承,并将你的循环放在其中。

答案 1 :(得分:0)

问题是参数customForm属于object类型,它没有名为Controls的属性。尝试更改参数类型:

public void FormatDateTimePickers(Form customform)
{
    foreach (Control c in customform.Controls)
    {
        var dateTimePicker = c as DateTimePicker;
        if (dateTimePicker != null)
        {
            dateTimePicker.Format = DateTimePickerFormat.Custom;
            dateTimePicker.CustomFormat = "dd/MM/yyyy";
        }
    }
}