简体   繁体   中英

How to change property of usercontrol dynamically in loop

1 I have problem that I am going to work with usercontrol in loop. In other word II want to change usercontrols property, but I cant. So I have usercontrol named ucProperty and in it many labels. I have called all of them differently such as LblNameModel , LblImageName , ... In my form there are many usercontrols - ucProperty1,2,.8 and now I want to change their properties ( LblNameModel, LblImageName,.. ) dynamically and in loop. I try this:

int i = 1;
foreach (Control contrl in this.Controls) 
{
   if (contrl.Name == ("ucProperty" + i.ToString())) 
   {
      contrl.LblNameModel = "Model" + i.ToString();
      contrl.LblImageName = "image" + i.ToString() + ".jpg";
      i++;
   }
}

enter image description here LblNameModel isnt accepted

But it doesnt work. My problem is properties as LblNameModel after contrl. isnt accepted to programm. How I can change the properties in loop

and in my usercontrol ucProperty there is the code:

public string LblNameModel
{
    get { return lblNameModel.Text; }
    set { lblNameModel.Text = value; }
}

this is next result

You must filter and cast to your user controls

using System.Linq;

...

foreach (var uc in this.Controls.OfType<MyUserControlType>()) 
{
   string number = uc.Name.SubString("ucProperty".Length);
   uc.LblNameModel = "Model" + number;
   uc.LblImageName = "image" + number + ".jpg";
}

If you simply loop through the controls, you get a loop variable typed as Control and you are not able to access properties specific to your user control. The OfType<T> extension method (namespace System.Linq ) does both, filter and cast.

I assume that all of these user controls are named as ucProperty<number> . Otherwise add the check

if (uc.Name.StartsWith("ucProperty"))

Note that your approach with i has a problem if the user controls do not appear in the right order. Ie If the foreach yields "ucProperty4" but i is 3 then this control will be skipped.

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