[英]How can I acces drag-and-drop buttons by String in a loop?
I am working on a desktop application which includes graphic scheme and that scheme has 50 drag-and-drop buttons(they are not dynamically allocated) they are all named similar(for example button 1 is btnP1, button 2 is btnP2 etc...). 我正在一个包含图形方案的桌面应用程序上工作,该方案有50个拖放按钮(它们不是动态分配的),它们都被命名为相似的(例如,按钮1是btnP1,按钮2是btnP2等... )。 I would like to access those buttons with a for loop using string, I checked some previous posts on this site but none of those answers helped my problem. 我想使用字符串使用for循环访问这些按钮,我检查了此站点上的一些以前的文章,但是这些回答都没有解决我的问题。
I wrote 50 lines of codes to add those buttons to controls, and the same moment I add them to the controls they disappear from the graphic scheme. 我编写了50行代码,将这些按钮添加到控件中,与此同时,我将它们添加到控件中的那一刻,它们从图形方案中消失了。 Later I tried to access them through for loop, but nothing happened, since they disappear once I add them to the controls.. 后来我尝试通过for循环访问它们,但是什么也没发生,因为一旦将它们添加到控件中,它们就会消失。
this.Controls.Add(btnP1);
this.Controls.Add(btnP2);
this.Controls.Add(btnP3);
this.Controls.Add(btnP4);
... and so on
this.Controls.Add(btnP47);
this.Controls.Add(btnP48);
this.Controls.Add(btnP49);
this.Controls.Add(btnP50);
for(int i = 1; i <= 50; i++)
{
this.Controls["btnP"+ i.ToString()].Visible= False;
}
I would like to find out if there is some other way to access my buttons, because I need them to be shown and hidden. 我想了解是否还有其他方法可以访问我的按钮,因为我需要显示和隐藏它们。
To loop over all buttons within one control you can use a foreach
loop 要遍历一个控件中的所有按钮,可以使用foreach
循环
foreach(Button btn in this.Controls.OfType<Button>())
{
btn.Visible = false; //every button in you Control
}
With this code lines you run through the entire Control
. 使用此代码行,您可以遍历整个Control
。
With the OfType
method you filter only the buttons out of the control. 使用OfType
方法,您只能将按钮过滤出控件。 So you prevent an InvalidCastException
error. 因此,您可以防止InvalidCastException
错误。
Similar to Mario's answer but I would probably expand the selectors if their naming is consistent and filter out ones that can't be dropped: 与Mario的答案类似,但是如果选择器的命名一致,我可能会扩展它们,并过滤掉不能删除的选择器:
foreach (Button btn in this.Controls.OfType<Button>().Where(x => x.Name.StartsWith("btnP") && x.AllowDrop))
{
btn.Visible = false;
}
LINQ version: LINQ版本:
this.Controls
.OfType<Button>()
.Where(b => b.Name.StartsWith("btnP") && b.AllowDrop)
.ToList()
.ForEach(b => b.Visible = false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.