0

在编写连接两个 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!";
        }

    }

为什么会这样?

4

1 回答 1

0

这是正常行为。如果不将控件添加到Controls 集合中,ASP.NET 框架将不会在回发中保留其值,因此会在回发期间丢失。

于 2011-09-07T04:45:44.537 回答