2016-11-09 39 views
0

我有一个应用程序,其中我有内部,以便区分它们许多按键,我创建一个类中,我把这个: 我不得不说,我的按钮是在FlowLayoutPanel。无法转换类型的对象“System.Windows.Forms.FlowLayoutPanel”到“System.Windows.Forms.Button C#

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; 

       } 
      } 

     } 

但是我在标题中出现了错误,你有什么想法吗?

无法转换类型 'System.Windows.Forms.FlowLayoutPanel' 的目标,以“System.Windows.Forms.Button

谢谢。

+1

的可能的复制[走走无法投类型的对象,通过Button控件上的表单试图循环时,错误](HTTP: //stackoverflow.com/questions/28468613/ge tting-unable-cast-object-of-type-error-when-trying-to-loop-through-button) – Sinatr

+0

目前还不清楚你正在搜索的按钮位于何处。它包含在FlowLayoutPanel控件集合中还是在表单控件集合中? – Steve

+0

我的按钮是flowpanel – Sheva07

回答

1

这行不正确

foreach (Button c in f1.Controls) 

在这里,您认为在F1中的每个控件是一个按钮,这样也文本框和其他控件会触发你的错误。相反,如果你想只按键更改您的代码

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

请记住,这会发现只有那些直接包含在窗体的Controls集合按钮。如果他们是另一个容器内(如组框或面板)线以上将无法正常工作,你应该使用合适的容器或递归调用来遍历所有的控件集合

编辑

如果你的按钮在FlowLayoutPanel中的控件集合内,则代码应该搜索该集合中的按钮

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

将需要递归到子控件好吧,虽然,例如http://stackoverflow.com/questions/1558127/how-can-i-get-all-controls-from-a-form-including-controls-in-any-container – stuartd

+0

我只是写一下。但是,该答案不使用OfType扩展。搜索一个笨蛋,,,, – Steve

+0

根据OP,按钮不在'f1';他们在'fk'。 – adv12

相关问题