目前,正在做一個asp.net 2.0項目,其中使用了複合控件。
在一個頁面上放置了GridView控件用於顯示多條數據的摘要信息,同時,放置了若干小控件(包括複合控件)來顯示詳細資料,GridView控件中有Command字段“詳細”來處理。(也可以分爲兩個頁面佈局,圖省事,放在一起了,:>)。在使用過程中發現一個奇怪的現象:第一次點“詳細”時,一切正常顯示;後面的數據涉及到複合控件的信息就不能正常顯示了。經調試發現,原因是程序執行路徑不完全一樣,最主要的是複合控件的CreateChildControl。 很明顯是同一個頁面上控件創建一次就OK了,但後果是第一次查看的數據可以正常綁定複合控件,後面的就不行了(見代碼1)。雖然每次給控件賦值(代碼3)都會調用代碼2的Set操作,但不會調用代碼1的最後一句。這就導致了最初的怪現象。 //代碼1 protected override void CreateChildControls() { //base.CreateChildControls(); #region 控件初始化
_tbxFinalPersonList = new TextBox(); _tbxFinalPersonList.ID = "tbxFinalPersonList"; _tbxFinalPersonList.ReadOnly = true; _tbxFinalPersonList.Width = TextWidth; _tbxFinalPersonList.Height = TextHeight; _tbxFinalPersonList.TextMode = TextMode; _tbxFinalPersonList.Text = ViewState["PersonNameList"] == null ? string.Empty : ViewState["PersonNameList"].ToString();
...創建其他控件 }
//代碼2 複合控件屬性:
public string PersonNameList { get { return _tbxFinalPersonList.Text; } set { ViewState["PersonNameList"] = value; CreateChildControls();//710 //_tbxFinalPersonList.Text = value; }//2008.5.16孫宜貴,2008-5-19孫宜貴 7-9孫宜貴 }
//代碼3 this.PersonList1.PersonNameList = papaerModule.AuthorName;//得到獲獎人員列表
所以,只好在每次綁定時,重新調用代碼1,但是重複創建仍然會產生錯誤,後來把代碼1改造後(代碼4)就通過了。 //代碼4 protected override void CreateChildControls() { //base.CreateChildControls(); #region 控件初始化 if (_tbxFinalPersonList == null) { _tbxFinalPersonList = new TextBox(); _tbxFinalPersonList.ID = "tbxFinalPersonList"; _tbxFinalPersonList.ReadOnly = true; _tbxFinalPersonList.Width = TextWidth; _tbxFinalPersonList.Height = TextHeight; _tbxFinalPersonList.TextMode = TextMode;
...創建其他控件 } _tbxFinalPersonList.Text = ViewState["PersonNameList"] == null ? string.Empty : ViewState["PersonNameList"].ToString(); }