1
如果標題看起來荒謬,我很抱歉。我試圖理解兩種情況下的答案,我陷入困境。我在按鈕單擊時動態創建用戶控件,同時跟蹤視圖狀態中的計數。以下是代碼:ViewState在回發頁面上沒有價值/頁面生命週期的哪個階段是要使用的視圖狀態
private int custControlCountID;
public int CustControlCountID
{
get
{
return (int)(ViewState["CustControlCountID"] == null? 1 : ViewState["CustControlCountID"]);
}
set
{
ViewState["CustControlCountID"] = value;
}
}
protected void Page_Init(object sender, EventArgs e)
{
for (int i = 0; i < CustControlCountID; i++)
{
RejRow customControl = (RejRow)LoadControl("~/RejRow .ascx");
customControl.ID = "rejRow" + i;
divHolder.Controls.Add(customControl);
}
}
protected void btnNewRow_Click(object sender, EventArgs e)
{
CustControlCountID = CustControlCountID + 1;
RejRow customControl = (RejRow)LoadControl("~/RejRow.ascx");
customControl.ID = "rejectRow" + CustControlCountID;
divHolder.Controls.Add(customControl);
}
我只分享了相關的代碼。在單擊按鈕控件上添加成功,但只有一次。這是因爲Page_Init上的CustControlCountID始終設置爲1。 我已經瞭解到,LoadViewState在Page_Init之後被調用,因此我設置的值在Page_Init中不可用。我還了解到,在控制層次結構建立期間,控件將被添加到Page_Init中。請幫我理解這一點。
你有沒有嘗試覆蓋'CreateChildControls'方法來添加控件而不是'Page_Init'? – 2013-02-25 10:41:22