Enabling view state does not work with controls in a web part

What I have?

I have a simple web part with Table

. The table has two controls: a TextBox

and a Button

. In the method, CreateChildControls()

I add controls to the table if !Page.IsPostBack

true. And the table has a view state.

What do I want to do?

I want the controls in the table to be present after the post.

What problem am I facing?

I am excluding the controls, TextBox

and Button

, which will be present in the table after the post back. But that doesn't happen.

I feel like creating the entire table in each column is a little expensive and enabling view state will solve this problem.

Can anyone tell me that I am missing something?

Thanks in advance!

Update:

I tried setting a EnbleViewState

web part property . All the same result.

code:

public class TreeWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private Table table;
        private Button clickMe;
        private TextBox content;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            BuildTable();
        }

        private void BuildTable()
        {
            table = new Table();
            clickMe = new Button();
            content = new TextBox();

            table.ID = "myTable";
            table.EnableViewState = true;

            if (!this.Page.IsPostBack)
            {
                clickMe.Text = "Click Me!";
                clickMe.Click += new EventHandler(clickMe_Click);

                content.Text = "Click button to set text";
                content.Width = Unit.Pixel(200);

                TableCell cell = new TableCell();
                cell.Controls.Add(content);

                TableRow tr = new TableRow();
                tr.Cells.Add(cell);
                table.Rows.Add(tr);

                cell = new TableCell();
                cell.Controls.Add(clickMe);

                tr = new TableRow();
                tr.Cells.Add(cell);
                table.Rows.Add(tr);

            }
            this.Controls.Add(table);
        }

        protected void clickMe_Click(object sender, EventArgs e)
        {
            content.Text = DateTime.Now.ToLongDateString() + "  " + DateTime.Now.ToLongTimeString();
        }
    }

      

+2


source to share


1 answer


Because view state only persists changed control state through callbacks and not the actual controls themselves, dynamically added controls must be added to the ASP.NET Web page both on the initial visit and in all subsequent postbacks. For more information visit here .



+1


source







All Articles