Reputation: 3
1I 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; }
}
Upvotes: 0
Views: 48
Reputation: 112342
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. I.e. If the foreach
yields "ucProperty4"
but i
is 3
then this control will be skipped.
Upvotes: 1