[英]Page_Load not firing in UserControl
我已經在類庫中的c#中創建了一個類,並且我已將此控件添加到default.aspx中,但是我的代碼沒有觸發page_load事件。 這是代碼:
我做錯了什么?
頁面加載但不顯示頁面上的標簽。 我已將控件正確添加到頁面中,沒有任何錯誤。 我有事件在那里添加了寄存器標簽。
html標記: <RandoIntegerControls:RandomIntegerControl ID="RandomIntegerControl1" runat="server"></RandoIntegerControls:RandomIntegerControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
namespace CSIMedia.WebControls
{
public class RandomIntegerControl : PlaceHolder
{
private Label _Label;
public RandomIntegerControl()
{
}
private void Page_Load(Object sender, EventArgs e)
{
this._Label = new Label();
this.Controls.Add(this._Label);
this._Label.Text = "Enter random values:";
}
}
}
Default.aspx頁面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="RandoIntegerControls" Assembly="CSIMedia.WebControls" Namespace="CSIMedia.WebControls"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<RandoIntegerControls:RandomIntegerControl ID="RandomIntegerControl1" runat="server"></RandoIntegerControls:RandomIntegerControl>
</div>
</form>
</body>
</html>
試試這個:
public RandomIntegerControl()
{
this.Load += Page_Load;
}
在頁面(和用戶控件)中,由於此屬性,Page_Load方法通常會自動附加:
<%@ Page ... AutoEventWireup="true" ... %>
如果你沒有aspx / ascx文件,它不會自動發生,但你仍然可以使用上面的代碼手動連接它。
您繼承自PlaceHolder,它是一個Web控件,不會處理Page_Load事件。 只有用戶控件(.ascx)才能隱式處理該事件。
根據您發布的代碼的外觀,您最好使用UserControl,或者如果您需要在多個項目中重用它,請從頭開始創建Web控件。
事實證明,您可以覆蓋aspx
標記文件中的Page_Load
。 該文件繼承自基本文件。
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="TestUserControl.ascx.cs" Inherits="TestUserControl" %>
覆蓋示例:
<script language="C#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
...
}
</script>
此函數會覆蓋代碼隱藏版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.