简体   繁体   English

在foreach循环中更改Control属性

[英]Changing Control property in foreach loop

I am trying to force controls in a TableLayoutPanel to be enabled (I disable the controls individually before). 我试图强制启用TableLayoutPanel中的控件(我之前分别禁用了控件)。

Using this code does not change anything (I remember foreach can not effect the items that are being looped over!). 使用此代码不会更改任何内容(我记得foreach不会影响正在循环的项目!)。 I guess there should be some casting or something to make it work: 我猜应该有一些强制转换或使其起作用的方法:

foreach(Control ctrl in myTable.Controls)
{
    ctrl.Enabled = true;
}

myTable is itself inside another table...if it is needed to be pointed out. myTable本身位于另一个表中...如果需要指出。 The controls I want to enable again are of type TextBox and DomainUpDown . 我要再次启用的控件的类型为TextBoxDomainUpDown

Here's an example that shows you can adjust the property like you are looking to do. 这是一个示例,显示您可以按期望的方式调整属性。 But you cannot change the reference you are iterating over itself. 但是您不能更改要对其自身进行迭代的引用。 Try this out and see if it clarifies anything. 试试看,看看是否可以澄清。

public class BasicClass
{
    public int BasicProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<BasicClass> lst = new List<BasicClass>();
        lst.Add(new BasicClass {BasicProperty=5});
        lst.Add(new BasicClass { BasicProperty = 6 });
        foreach (var item in lst)
        {
            item.BasicProperty++;
        }

        Console.WriteLine("{0}, {1}", lst[0].BasicProperty, lst[1].BasicProperty);
        Console.ReadLine();
    }
}

TableLayout isn't a control container, despite the fact that it seems so. 尽管看起来如此, TableLayout并不是控件容器。 So, you should iterate some other container to find your controls. 因此,您应该迭代其他一些容器来查找控件。

     //MyparentControl is the parent control of myTable
     //so assuming 0 is the index of "myTable" 

     for (int h = 0; h < MyparentControl.Controls[0].Controls.Count; h++)
        {
            MyparentControl.Controls[0].Controls[h].Enabled = true;
        }

Really sorry for bothering...apparently after scratching my head for few hours I found that the problem was because the table itself was set to Enabled = false somewhere in the code. 非常抱歉打扰一下……显然在after了几个小时后,我发现问题出在表中,原因是表本身在代码中的某处设置为Enabled = false I took care of that and the problem is solved. 我已经解决了,问题就解决了。 Thanks all for your inputs. 感谢大家的投入。

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

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