View Full Version : How to access property of user control with variable ID?

11-23-2012, 02:14 AM
Hello everybody.
I have two instances of same user control.
This user control has a property.
Each instance has different value of this property and different ID.
For example:

<uc:UserControl ID="UC1" runat="server" prop="value1" />
<uc:UserControl ID="UC2" runat="server" prop="value2" />
I want to get the value of prop of specific user control, depending on a condition.
I try to do this by the following code:

int I;
UserControl UC;
if (condition) {
I = 1;
} else {
I = 2;
UC = (UserControl)FindControl("UC" + I);
string Prop = UC.prop;
But this code give an error said that UC doesn't have a property called prop.
Of course this error occurred because UC didn't compiled in design mode.
How I can solve this problem?
Thanks for any reply.

11-23-2012, 03:01 PM
Without seeing the UC code it is going to be near impossible to answer- at first glance I don't see anything that would be 'wrong'... provided that those controls have a property called 'prop'. if it is not compiling then there is something wrong, and trying to correct something that you don't know why it's 'wrong' with outstanding compilation errors is also near impossible... you may simply have something wrong with a snip of code somewhere that makes the objects not build- who knows...

here's an example of two drop down list objects being accessed that reside on same page and their properties being accessed (note it is similar to your attempts)

List<ListItem> li_actions = new List<ListItem>();
li_actions.Add(new ListItem("Select...", "0"));
li_actions.Add(new ListItem("******1", "1"));
li_actions.Add(new ListItem("*******2", "2"));
li_actions.Add(new ListItem("*******3", "3"));
li_actions.Add(new ListItem("******4", "4"));
foreach (ListItem li in li_actions)

ddl_AddUpdateUser.SelectedIndexChanged += new EventHandler(ProcessIndex);
ddl_AddUpdateUser.AutoPostBack = true;

List<ListItem> li_NewUserTypes = new List<ListItem>();
li_NewUserTypes.Add(new ListItem("Select...", "0"));
li_NewUserTypes.Add(new ListItem("New ******1", "1"));
li_NewUserTypes.Add(new ListItem("New ******2", "2"));
li_NewUserTypes.Add(new ListItem("New *******3", "3"));
foreach(ListItem li in li_NewUserTypes)

ddl_AddUserType.SelectedIndexChanged += new EventHandler(ProcessIndex);
ddl_AddUserType.AutoPostBack = true;
ddl_AddUserType.Visible = false;

See? I am able to access the dropdownlist object's properties without errorring out; also not that the method in there 'setDDLIndex()' also accesses the dropdownlist objects properties...

Let's first focus on 'why' your code is not compiling and resolve those problems first; then move on to why your attempts to access properties are failing out

Worth noting... if that property is a private property, then it will error out with that message (or something similar), because to the outside world (code included) that property does not exist. <- that may be your problem