Find a control in a webform

前端 未结 2 475
忘了有多久
忘了有多久 2020-12-03 08:13

I have a Web content form and need to access a control inside the content panel. I know of two ways to access the control:

  1. TextBox txt = (TextBox)Page.Co
2条回答
  •  情深已故
    2020-12-03 09:03

    I would like to change your GetControls function to a generic one as follows:

    public static T GetControl(this Control control, string id) where T:Control
    {
        var result = control.Controls.Flatten(c => (c.GetType().IsSubclassOf(typeof(T))) && (c.ID == id)).SingleOrDefault();
        if (result == null)
            return null;
        return result as T;
    }
    

    And Then,

    public static Control GetControl(this Control control, string id)
    {
        return control.GetControl(id);
    }
    

    This way, the caller would call something like:

    var button = Page.GetControl

提交回复
热议问题