user3882781
user3882781

Reputation: 59

ASP NET: Is it possible to set control property dynamically?

On my aspx page has a button. I want to change its property dynamically.

For example: A button which ID is Button1 and I want to change its property Visible to false. On code behind have three variables hidefield = "Button1", property = "Visible" and value = false. Is it possible to set the property Visible using the variables?

aspx:

<asp:Button ID="Button1" runat="server" Text="Button1" />

code behind:

protected void Page_Load(object sender, EventArgs e)
{
    string hidefield = "Button1";
    string property = "Visible";
    bool value = false;
    if (!IsPostBack)
    {
        Control myControl1 = FindControl(hidefield);
        if (myControl1 != null)
        {
            myControl1.property = value; // <- I know this statement has error. Is there any way to set the property like this?
        }
    }
}

Upvotes: 2

Views: 1544

Answers (3)

Mudassir Hasan
Mudassir Hasan

Reputation: 28741

protected void Page_Load(object sender, EventArgs e)
{
    string hidefield = "Button1";
    string property = "Visible";
    bool value = false;
    if (!IsPostBack)
    {
       /* Use below two lines if you are using Master Page else you wouldnot be able to access your control */

        ContentPlaceHolder MainContent = Page.Master.FindControl("MainContent") as ContentPlaceHolder;
        Control myControl1 = MainContent.FindControl(hidefield);

        if (myControl1 != null)
        {
             myControl1.GetType().GetProperty(property).SetValue(myControl1,value,null);  
        }
    }
}

Upvotes: 1

Jon P
Jon P

Reputation: 19772

Using reflection, based on Set object property using reflection

using System.Reflection;

protected void Page_Load(object sender, EventArgs e)
{
    string hidefield = "Button1";
    string property = "Visible";
    bool value = false;
    if (!IsPostBack)
    {
        Control myControl1 = FindControl(hidefield);
        if (myControl1 != null)
        {
            myControl.GetType().InvokeMember(hidefield ,
               BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
               Type.DefaultBinder, myControl, value);
        }
    }
}

It's pretty messy and not very human readable so therefore could have maintainablility issues.

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

how about this:

Button myControl1 = FindControl(hidefield) as Button;

 if (myControl1 != null)
 {
    myControl1.Visible= value; 
 }

Upvotes: 0

Related Questions