【发布时间】:2017-07-08 06:01:27
【问题描述】:
我在Form1 上有一些按钮。我想将他们的FlatStyle 属性设置为FlatStyle.Popup。
我搜索并编写了一些代码如下:
// List<Control> ButtonsList = new List<Control>();
List<Button> ButtonsList = new List<Button>();
public Form1()
{
InitializeComponent();
this.Icon = Properties.Resources.autorun; //Project->Properties->Resources->
ButtonsList = GetAccessToAllButtons(this).OfType<Button>.ToList(); //*** hot line ***
foreach(Button btn in ButtonList)
{
btn.FlatStyle = FlatStyle.Popup;
}
}
public IEnumerable<Control> GetAccessToAllButtons(Control thisClass)
{
List<Control> ControlsList = new List<Control>();
foreach (Control child in thisClass.Controls)
{
ControlsList.AddRange(GetAccessToAllButtons(child));
}
ControlsList.Add(thisClass);
return ControlsList;
}
但是当我在代码的热线中使用GetAccessToAllButtons() 时,VS 会产生这个错误:
'System.Linq.Queryable.OfType(Query.Linq.IQueryable)' 是一个 'method',在给定的上下文中无效
我的错误是什么?
编辑:我在here 的参考错过了()。这是一个公认的答案!在我的参考中,我们有不同的情况吗?还是只是一个错字?
【问题讨论】:
-
你有多少个按钮?如果是 10 或 20,您可以创建一个数组来保存对按钮变量的引用,而不是编写递归?例如
var buttons = new Button[] {button1, button2, button3 }还是你添加按钮动态形成? -
@shahkalpesh 我有 14 个按钮,并在加载表单时添加它们,而不是动态地。
-
虽然您已经得到答案,但我认为将 14 个变量名称添加到按钮数组而不是尝试在运行时查找按钮是可以的。
标签: c# winforms button visual-studio-2013