2

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?
        }
    }
}
Humayun Shabbir
  • 2,961
  • 4
  • 20
  • 33
  • You won't be able to use "property" as a variable. Also keep in mind `FindControl` isn't recursive, if you button is in another control it won't be found. – Jon P Jul 28 '14 at 02:24

3 Answers3

1

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.

Community
  • 1
  • 1
Jon P
  • 19,442
  • 8
  • 49
  • 72
1
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);  
        }
    }
}
Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
0

how about this:

Button myControl1 = FindControl(hidefield) as Button;

 if (myControl1 != null)
 {
    myControl1.Visible= value; 
 }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160