代码之家  ›  专栏  ›  技术社区  ›  Patrick

在基类中使用aspx控件

  •  2
  • Patrick  · 技术社区  · 17 年前

    我有两个非常相似的aspx页面,在代码背后有各种相同的函数。我想创建一个基类,这两个代码隐藏类都是从这个基类派生的。基类是否可以访问aspx页上的控件。例如:

    class base
        inherits System.Web.UI.Page
        Sub prepareScreen()
           'txtName is a text box on the aspx page
           Me.txtName.text = "George"
        end sub
    end class
    
    class codeBehind
         inherits base
         Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
              prepareScreen()
         end sub
    end class
    

    在某种程度上可以理解,代码无法通过以下方式编译:

    'txtName' is not a member of 'clsbase'
    

    有可能把两者联系起来吗?

    5 回复  |  直到 11 年前
        1
  •  2
  •   Kirtan    17 年前

    如果你重构你的代码会更好,这样你就不需要做这样的事情了。

        2
  •  2
  •   David Clarke    11 年前

    您需要将控件声明为基类的属性。然后在ASP标记中,使用CodeFileBaseClass属性。

    这个 MSDN reference

    class base
        inherits System.Web.UI.Page
        Protected Property txtName() As TextBox
        Sub prepareScreen()
           'txtName is a text box on the aspx page
           Me.txtName.text = "George"
        end sub
    end class
    
    class codeBehind
         inherits base
         Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
              prepareScreen()
         end sub
    end class
    
    <%@ page CodeFileBaseClass="base" inherits="codebehind" ...  %>
    
        3
  •  0
  •   Program.X    17 年前

    TextBox txtName=FindControl("txtName");
    

        4
  •  0
  •   Sergio    17 年前

    您可以使用((TextBox)Page.FindControl(“txtName”)获取文本框。请小心,因为如果在其他可能不存在控件的地方使用此基类

        5
  •  0
  •   Sergio    17 年前

    您可以创建一个属性:

    protected TextBox txtName 
    {
    get{return (TextBox)Page.FindControl("txtName");} 
    set{Page.FindControl("txtName") = vale;}
    }
    

    protected virtual TextBox txtName{get;set;}
    

    在这种情况下,您必须在主类中重写它

      protected override TextBox txtName{/*same as above*/}