简体   繁体   English

通过名称查找特定控件并修改其.Value属性

[英]Find a specific control by name and modify its .Value property

I've found a few answers around that work fine with modifying .Text, .Checked values and so, but none of them worked when I tried changing the .Value property. 我已经找到了一些关于修改.Text和.Checked值等的答案,但是当我尝试更改.Value属性时,它们都无效。 I can't get that to work on progress bars. 我无法在进度条上使用它。 Last I tried: 最后我尝试了:

foreach (Control c in this.Controls)
{
    if (c.Name == "test" && c is ProgressBar)
    {
        ((ProgressBar)c).Value = 23;
    }
}

Am I missing a using statement or something? 我是否缺少using语句或其他内容?

Assuming that your progressbar control is named "test" (all lowercase letters) and is placed directly on the surface of your form (not inside a groupbox,panel or other control container) then this code should work and simplify your work 假设您的进度条控件被命名为“ test”(所有小写字母)并且直接放置在窗体的表面(不在组框,面板或其他控件容器内),那么此代码应该可以工作并简化您的工作

foreach (var c in this.Controls.OfType<ProgressBar>().Where(x => x.Name == "test") 
{
   c.Value = 23;
}

instead if the ProgressBar is placed inside a control container (like a panel) the above code should be changed to loop over the controls collection of the container 相反,如果将ProgressBar放置在控件容器(如面板)中,则应更改以上代码以遍历容器的控件集合

foreach (var c in this.panel1.Controls.OfType<ProgressBar>().Where(x => x.Name == "test") 
{
   c.Value = 23;
}

As pointed out in the comment by KingKing , if you are absolutely sure that a control named "test" exists in your groupbox then a simple lookup in the controls collection should result in your progressbar. 正如KingKing的评论中指出的那样 ,如果您完全确定组框中存在一个名为“ test”的控件,则在控件集合中进行简单查找就可以显示进度条。 Looping is not necessary in this case 在这种情况下,不需要循环

ProgressBar pb = this.groupBox1.Controls["test"] as ProgressBar;
if(pb != null) pb.Value = 23;

The trick here is that Controls is not a List<> or IEnumerable but a ControlCollection. 这里的技巧是,控件不是List <>或IEnumerable,而是ControlCollection。

I recommend using an extension of Control. 我建议使用Control的扩展。 Add this class to your project: 将此类添加到您的项目中:

public static class ControlExtensionMethods
{
    public static IEnumerable<Control> All(this System.Windows.Forms.Control.ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }
}

Then you can do : 然后,您可以执行以下操作:

foreach(var textbox in this.Controls.All())
{
    // Apply logic to a control
}

Source: Click 来源: 点击

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM