Raj
Raj

Reputation: 871

How can i access a server side control from asp.net code behind file using reflection?

For example, if i have on the aspx page:

<asp:PlaceHolder ID="tab_0" runat="server" Visible="false"></asp:PlaceHolder>
<asp:PlaceHolder ID="tab_1" runat="server" Visible="false"></asp:PlaceHolder>

and i want to access these properties in the code behind page using values from a configuration file for example

string enabledTabs = "0,1,2,3";

if there a way i can use reflection to set them to enabled or disabled e.g.

foreach(var id in enabledTabs.Split(',')) 
{
  // <use reflection to get the correct tab control>

  // Set property of the tab
  tab.Visible = true;
}

I could acheive the result i want by using a switch statement and setting the particular control property, but i'd like to use reflection to get the tab to make it cleaner.

Could anyone help?

Thanks!

Upvotes: 0

Views: 1703

Answers (3)

Nealv
Nealv

Reputation: 6884

Try the following:

Control tab = Control.FindControl("tab_"+id);

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245459

You don't need reflection. Use Page.FindControl:

foreach(var id in enabledTabs.Split(','))
{
    PlaceHolder control = (PlaceHolder)this.FindControl("tab_"+id));
    control.Visible = true;
}

Upvotes: 3

rick schott
rick schott

Reputation: 21137

foreach(var id in enabledTabs.Split(',')) 
{      

    // Set property of the tab
    Page.FindControl("tab_" + id.ToString()).Visible = true;
}

Upvotes: 1

Related Questions