Josh Cooper
Josh Cooper

Reputation: 191

Dynamically access the control name in code behinde

I have a series of divs which I want to show/hide depending on a the logged in user's userGroup.

<div id="divUserGroup1" runat="server" visible ="false"> 
</div>
<div id="divUserGroup2" runat="server" visible ="false"> 
</div>
<div id="divUserGroup3" runat="server" visible ="false"> 
</div>

I use the following to retreive the usergroup.

userGroup = Convert.ToInt32(Session["userGroup"]);

Is there a better way then doing the following.

if (userGroup == 1)
{
     divUserGroup1.Visible = true;
}
else if (userGroup == 2)
{
     divUserGroup2.Visible = true;
}

I was thinking some sort of divUsergroup" + userGroup + ".Visible = True

But I can't get anything to work.

Thanks

Upvotes: 0

Views: 54

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157136

You can use Page.FindControl to find a control by its name:

Control c = this.FindControl("divUsergroup" + userGroup);

if (c != null) // it exists?
{
    c.Visible = true;
}

(Note that this only finds top level controls)

Upvotes: 1

Related Questions