Home > Software engineering >  How to change CustomFormat of multiple DateTimePicker fields in Winforms using foreach loop in c#?
How to change CustomFormat of multiple DateTimePicker fields in Winforms using foreach loop in c#?

Time:01-05

I am trying to change CustomFormat of multiple DateTimePicker components in my Winforms form. However when I create foreach loop I dont get option to change CustomFormat. Here is the code:

foreach (Control ctrl in this.Controls)
            {
                if(ctrl is DateTimePicker)
                {
                    ctrl.CustomFormat = "yyyy-MM-dd"; 
                }
            }

I am getting error: "'Control' does not contain a definition for 'CustomFormat' and no accessible extension method 'CustomFormat' accepting a first argument of type 'Control' could be found (are you missing a using directive or an assembly reference?)".

I am using VS 2022, and .NET CORE 6 (latest stable version).

Any help with this will be more than welcomed.

CodePudding user response:

That's because you're still using variable "ctrl" which type is Control - not a DateTimePicker

foreach (Control ctrl in this.Controls)
{
    if(ctrl is DateTimePicker dtp)
    {
        dtp.CustomFormat = "yyyy-MM-dd"; 
    }
}

Should work just fine.

  •  Tags:  
  • Related