ASP NET:是否可以动态设置控件属性?

时间:2014-07-28 01:43:51

标签: asp.net

在我的aspx页面上有一个按钮。我想动态更改其属性。

例如: ID为Button1的按钮,我想将其属性Visible更改为false。 在代码背后有三个变量hidefield = "Button1"property = "Visible"value = false。 是否可以使用变量设置属性Visible?

ASPX:

<asp:Button ID="Button1" runat="server" Text="Button1" />
代码背后的代码:

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?
        }
    }
}

3 个答案:

答案 0 :(得分:1)

使用反射,基于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);
        }
    }
}

它非常混乱,并且不具备人类可读性,因此可能存在可维护性问题。

答案 1 :(得分:0)

怎么样:

Button myControl1 = FindControl(hidefield) as Button;

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

答案 2 :(得分:0)

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);  
        }
    }
}
相关问题