在编写连接两个 webpart 的代码时,我创建了两个标签。两个标签的文本值都是用 OnPreRender 方法编写的。但是,我忘记在 CreateChildControl 方法中为一个标签添加控件。因此,在调试时,我注意到,在回发后,我忘记添加其控件的标签没有保留该值,并且显示为空字符串。但是我添加的另一个控件的标签能够保留该值。
protected override void CreateChildControls()
{
base.CreateChildControls();
btnup.Text = " Update";
this.Controls.Add(lblid);//**If i add this, the label retains the value during post back , otherwise its null**
this.Controls.Add(lblname);
this.Controls.Add(lbldesig);
this.Controls.Add(tbdes);
this.Controls.Add(lblcomp);
this.Controls.Add(tbcomp);
this.Controls.Add(btnup);
btnup.Click += new EventHandler(btnup_Click);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (connectionInterface != null)
{
id = connectionInterface.parameter1;
SPWeb mysite = SPContext.Current.Web;
SPList mylist = mysite.Lists["UpdateList"];
SPListItemCollection itemcol = mylist.Items;
foreach (SPListItem itm in itemcol)
{
string nm = itm["Company_Id"].ToString();
if (nm.Equals(id))
{
lblid.Text = itm["Company_Id"].ToString();
lblname.Text = itm["Name"].ToString();
l
}
}
}
else
{
lblname.Text = "nothing is recieved!";
}
}
为什么会这样?