Sheva07 Sheva07 - 26 days ago 9
C# Question

Unable to cast object of type 'System.Windows.Forms.FlowLayoutPanel' to 'System.Windows.Forms.Button c#

I have an app where I have many buttons inside so to differentiate them, I create a class in which I put this:
I have to say that my button is in a FlowLayoutPanel.

public static void SetButtonPos(Form f1,FlowLayoutPanel fk)
{



foreach (Button c in f1.Controls)
{

if(c.Name.Contains("BTN_Menu"))
{
c.Size= new Size(247, 45);
c.BackColor = ColorTranslator.FromHtml("#373737");
c.ForeColor = ColorTranslator.FromHtml("#FFFFFF");
c.FlatStyle = FlatStyle.Flat;
c.FlatAppearance.BorderSize = 0;
c.TextAlign = ContentAlignment.MiddleLeft;
c.TextImageRelation = TextImageRelation.ImageBeforeText;
c.Height = 45;
c.Width = fk.Width - 6;

}
}

}


But I got the error in the title, do you have any idea ?


Unable to cast object of type 'System.Windows.Forms.FlowLayoutPanel' to 'System.Windows.Forms.Button


Thank you.

Answer

This line is incorrect

foreach (Button c in f1.Controls)

Here you consider that each control in f1 is a button, so also textboxes and other controls will trigger your error. Instead if you want only buttons change your code to

foreach (Button c in f1.Controls.OfType<Button>())

Keep in mind that this will find only Buttons that are directly contained in the Controls collection of your form. If they are inside another container (like a groupbox or panel) the line above will not work and you should use the appropriate container or a recursive call to traverse every Controls collection

EDIT

If your button is inside the controls collection of the FlowLayoutPanel then the code should search your button in that collection

foreach (Button c in fk.Controls.OfType<Button>())
Comments