![](/img/trans.png)
[英]Can I call page_load event of usercontrol before page_load event of aspx page?
[英]How to catch an event before Page_Load
我在ASP及其生命周期中遇到一個經常性的問題,即在Page_Load事件引發之前捕獲事件。 例如,這里我自定義了一個gridview,它繼承自gridView類。 我添加了一個下拉列表以選擇要跳轉的頁面(PageIndexChanged)。 一切都會很棒,除了我渲染它之后會調用此dropdownlist的SelectedIndexChanged事件(網格和我的下拉菜單在每次回發時都會重新生成)。 因此,我無法在其中選擇正確的值。
因此,我的活動僅在第二次回發時提出,我總是遲到一個回發。
該下拉列表添加在RowCreated事件上。 我在其他事件中嘗試過,但是它是為時已晚還是為時太早(如果太晚則不會渲染,如果太早則不會丟失元素)。
有什么辦法嗎?
PS:我發現這篇文章對我有幫助,但是我不知道該怎么做:
進行控制或繼承/擴展時要考慮的要點:
- 您必須通過重寫在調用base.CreateChildControls()的位置上的CreateChildControls來創建要引發事件的任何項目,然后執行所需的任何操作(即在您的情況下添加行)。
- 列表項DataBinding的呈現方式非常……不符合要求。...您應該通過重寫DataBind()來簡化它,以使其清除子級,然后調用確保兒童控件(),然后添加新的Rows ...這樣,很好的ViewStated,持久化和事件管理功能。 簡單得多。
- 再次列出項目:也不要太早創建子級:避免直接在OnInit或onLoad中創建子級控件。 這是一個錯誤。 最好的辦法是讓系統在需要時調用確保兒童控件(它將在第一頁加載時在PreRender中,在回發時,如果它具有子級事件,則在OnInit之后調用它)。更糟糕的是,讓OnInit,OnLoad調用SecureChildControls()。
您所關注的msdn頁面是ASP.NET頁面生命周期概述 ,它具有一個有用的表,可以告訴您整個頁面生命周期中發生的所有事件。
您可能需要以下其中一項(來自上面的鏈接):
預初始化
在開始階段完成之后且初始化階段開始之前引發。
將此事件用於以下用途:
在里面
在初始化所有控件並應用任何外觀設置之后引發。 各個控件的Init事件發生在頁面的Init事件之前。
使用此事件讀取或初始化控件屬性。
初始化完成
在頁面初始化階段結束時引發。 在Init和InitComplete事件之間僅發生一項操作:啟用對視圖狀態更改的跟蹤。 視圖狀態跟蹤使控件能夠保留以編程方式添加到ViewState集合的所有值。 在打開視圖狀態跟蹤之前,添加到視圖狀態的所有值都會在回發過程中丟失。 控件通常在引發Init事件后立即打開視圖狀態跟蹤。
使用此事件進行更改,以查看要確保在下一次回發之后仍保留的狀態。
預載
在頁面加載自身及其所有控件的視圖狀態之后,以及在處理請求實例所包含的回發數據之后引發。
確定它似乎終於我解決我的問題感謝我上面給的文章, 而這其中 ,很多搜索的:
public class MyGridView : GridView
{
TextBox txtSearch;
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
int numRows = base.CreateChildControls(dataSource, dataBinding);
// Create a new row
GridViewRow rowSearch = base.CreateRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
//convert the existing columns into an array, initialize and then add the row to the previously created table
DataControlField[] fields = new DataControlField[this.Columns.Count];
this.Columns.CopyTo(fields, 0);
this.InitializeRow(rowSearch, fields);
TableCell cellSearch = new TableCell();
rowSearch.Cells.Add(cellSearch);
txtSearch = new TextBox();
txtSearch.Text = this.SearchTextboxDefaultValue;
txtSearch.ID = "txtSearch";
txtSearch.AutoPostBack = true;
txtSearch.TextChanged += new EventHandler(txtSearch_TextChanged);
cellSearch.Controls.Add(txtSearch);
this.Controls[0].Controls.Add(rowSearch); // Controls[0] is a Table element
return numRows;
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
string search = (sender as TextBox).Text;
DataTable dt = new DataTable();
// We fill in dt with results, and rebind it
this.DataSource = dt;
this.DataBind();
}
}
在Page.cs中:
private DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
sampleDataTable();
if (!Page.IsPostBack)
{
myGrid.DataSource = dt;
myGrid.DataBind();
}
}
private void sampleDataTable()
{
// Populate the dataTable
}
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.