日期:2014-05-19  浏览次数:20495 次

自定义控件子控件初始化问题,高手请进!
public   class   TripalCheckList   :   System.Web.UI.WebControls.WebControl
{
private   TextBox   txtListContent;
private   TextBox   txtListID;
private   string   _DataTextField;
                                    //构造函数
public   TripalCheckList()
{
txtListContent   =   new   TextBox();
txtListID   =   new   TextBox();
}
                                    protected   override   void   CreateChildControls()
{
txtListContent   =   new   TextBox();
txtListID   =   new   TextBox();
txtListContent.ID   =   this.ClientID   +   "_Text ";

txtListID.ID   =   this.ClientID   +   "_Value ";
base.CreateChildControls   ();
}
                                      public   string   SelectedListText
{
set
{
txtListContent.Text   =   value;
}
get
{
return   txtListContent.Text;
}
}
------在构造函数中初始化子控件,设计时拖拉到窗体可以呈现
但在获取子控件的值时,构造函数再次执行导致实例化一个新的子控件,丢失了值
如果不在构造函数中初始化子控件,则报错txtListContent未实例化
请问:怎么解决啊

------解决方案--------------------
将值保存到viewstate中
------解决方案--------------------
protected override void CreateChildControls()
{
txtListContent = new TextBox();
txtListID = new TextBox();
txtListContent.ID = this.ClientID + "_Text ";

txtListID.ID = this.ClientID + "_Value ";
base.CreateChildControls ();
}
偶的理解.
貌似构造函数里面NEW 了这里就不需要new TextBox()了..
------解决方案--------------------
你的写法很奇怪哦,不过我建议你试着让.net自己去管理状态

protected override void CreateChildControls()
{
base.CreateChildControls();
txtListContent = new TextBox();
//添加到controls集合
this.Controls.Add(txtListContent);
....
}

------解决方案--------------------
当 TripalCheckList 作为控件显示在WebForm上.
刷新时引起的重新构造,使得这个实例丢失原来保存的值?