在编写连接两个web部件的代码时,我创建了两个标签。两个标签的文本值都是在OnPreRender方法中写入的。然而,我忘了在CreateChildControl方法中添加一个标签的控制。因此,在调试时,我注意到,post回来后,我忘记添加的控件的标签没有保留值,并且它显示空字符串。但是我添加的控件的另一个标签能够保留值。
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!";
}
}
为什么它是这样的行为?
这是正常的行为。如果您不将控件添加到Controls
集合中,则ASP。. NET框架将不会在回发中保留其值,因此将在回发期间丢失。