简体   繁体   中英

Changing Control property in foreach loop

I am trying to force controls in a TableLayoutPanel to be enabled (I disable the controls individually before).

Using this code does not change anything (I remember foreach can not effect the items that are being looped over!). 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. The controls I want to enable again are of type TextBox and DomainUpDown .

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. 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. I took care of that and the problem is solved. Thanks all for your inputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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