2011-04-11 56 views
1

我不明白爲什麼我的OnPreLoad函數不會被search.aspx.cs解僱。
* 更新* - 好的,我找出了導致問題的原因,但我不明白爲什麼它是一個問題。我更新了我的問題。asp.net OnPreLoad不會觸發?

這裏有三個相關文件:

// search.aspx -- THIS <select runat="server"> CAUSED ALL the problem 
<select runat="server" id="slctCategories"> 
    <asp:Repeater runat="server" ID="optCategories"> 
    <ItemTemplate> 
    <option value=""></option> 
    </ItemTemplate> 
    </asp:Repeater> 

</select> 

// search.aspx.cs 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Configuration; 

public partial class search : BTPage 
{ 
    protected override void OnPreLoad(EventArgs e) 
    { 
     base.OnPreLoad(e); 
    } 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

} 

// BTPage.aspx.cs - the file that search.aspx.cs inherits from 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Configuration; 

public partial class BTPage : System.Web.UI.Page 
{ 
    protected SqlConnection cnx; 

    protected override void OnPreLoad(EventArgs e) 
    { 
     cnx = new SqlConnection(ConfigurationManager.AppSettings["database"]); 
     cnx.Open(); 
    } 

    protected override void OnUnload(EventArgs e) 
    { 
     cnx.Close(); 
    } 

} 

什麼奇怪的是,onunload的DOES會被解僱。這是怎麼回事?爲什麼我的OnPreLoad不會啓動?

**更新** - 我得到了我的onpreload火我在search.aspx改變<select runat="server"><select>後。有人向我解釋爲什麼這解決了這個問題?我一直在爲此掙扎數小時。

+0

這很奇怪......你有沒有理由不使用'DropDownList'? – Town 2011-04-11 22:22:20

+0

是的,我剛剛偶然發現了asp:dropdownlist。我只用.net玩了大約1天 – John 2011-04-11 22:26:17

回答

1

有可能是你如何使用您的select一些奇怪的事情:

<select runat="server" id="slctCategories"> 
    <asp:Repeater runat="server" ID="optCategories"> 
     <ItemTemplate> 
      <option value=""></option> 
     </ItemTemplate> 
    </asp:Repeater> 
</select> 

你不應該嵌套一個Repeater該標籤內。我真的很驚訝,你沒有得到編譯/運行時錯誤。

您注意到您發現代替使用DropDownList控件。但是,HttpSelectList控件也具有用於向其添加項目的類似界面 - 您不需要在其中添加額外的列表控件。

我的猜測是,由於刪除作爲服務器控件解決了問題(修復了語法怪異問題),有一些微妙的事情阻止正常的OnPreLoad在該語法中被解僱。

1

在BTPage你不叫base.OnPreLoad:

protected override void OnPreLoad(EventArgs e) 
{ 
    cnx = new SqlConnection(ConfigurationManager.AppSettings["database"]); 
    cnx.Open(); 
} 

我不知道爲什麼會阻止搜索類中重寫的方法,不過,還是什麼select有什麼關係。 (例如,它應該已經工作了)。但是,在任何重寫的方法中調用基本方法通常都是一種很好的做法(即使這樣的方法專門爲您覆蓋)也是如此。你不知道是否應該發生在覈心Page.OnPreLoad方法中的任何其他事情。