2013-10-07 242 views
5

是否有可能從其他用戶控件繼承用戶控件?如何從其他UserControl繼承UserControl?

我試圖實現的是從另一個用戶控件繼承的用戶控件。所以我有baseusercontrol.ascx,這只是文字「東西」。然後我有另一個用戶控件,childusercontrol.ascx繼承baseusercontrol.ascx。如果我不更改childusercontrol.ascx中的任何內容,我會希望baseusercontrol.ascx文本顯示「Stuff」。

而且我應該能夠擴展派生的基本用戶控制功能。

我也試過類似this的東西,但是對我來說還不夠。

現在我childusercontrol.ascx看起來謊言之下

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="childusercontrol.ascx.cs" Inherits="test_childusercontrol" %> 
<%@ Register src="baseusercontrol.ascx" tagname="baseusercontrol" tagprefix="uc1" %> 

childusercontrol.ascx.cs如下

public partial class test_childusercontrol : baseusercontrol 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
} 

當我瀏覽這個網頁即時得到錯誤的

Object reference not set to an instance of an object. 
Description : An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details : System.NullReferenceException: Object reference not set to an instance of an object. 

任何線索?

+0

你能分享baseusercontrol.ascx的代碼嗎?您的錯誤表示您在特定行號處有空引用。我懷疑你有一個空引用。 o_O –

+0

您需要查看堆棧跟蹤,就像異常消息告訴您的一樣。幾乎所有的'NullReferenceException'都是一樣的。請參閱「[什麼是.NET一個NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」獲得一些提示。 –

+1

另外,不,用戶控件並不意味着被繼承。你可以做的最好的是創建繼承'UserControl'的基類,但不包含任何標記(沒有.ascx文件)。 –

回答

3

我已經爲自己測試了這種情況。其實你不能從一個基類UserControl繼承與它自己的ASCX代碼。

但是你可以做什麼,是實現的(可能是抽象)基類中的一些基本功能(不ASCX)是這樣的:

public class BaseClass:UserControl 
{ 
    public String BaseGreeting { get { return "Welcomebase!"; }} 
} 

然後使用這個基類的方法和屬性在具體UserControl類有自己的ASCX文件。

public partial class childusercontrol : BaseClass 
{ 
    protected override void OnInit(EventArgs e) 
    { 
     base.OnInit(e); 
     Greeting = base.BaseGreeting; //As initial value 
    } 
    public String Greeting 
    { 
     get { return LabelGreeting.Text; } 
     set { LabelGreeting.Text = value; } 
    } 
} 
相關問題