Solved

ASP.Net save viewstate of dynamic controls on post back

Posted on 2014-03-18
1
510 Views
Last Modified: 2014-03-19
Hi..
I have a page in which I'm adding controls dynamically during PAGE_INIT.
The controls are comboboxes in which a user selects a value.
I have a button that is clicked to search. Which calls code behind.
But my values get reset on POSTBACK. How do I enable viewstate on my dynamic controls.
So I can pass the selected values to the seacrh method.
thx
0
Comment
Question by:JElster
1 Comment
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
Comment Utility
You don't technically need to use the ViewState. You can simply rely on the fact that the values are posted back in the Request.Forms collection. So, say you do something like the following:
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            DropDownList ddl = new DropDownList();
            ddl.ID = "NewDropDown";
            ddl.Items.Add(new ListItem("One", "1"));
            ddl.Items.Add(new ListItem("Two", "2"));

            this.Form.Controls.Add(ddl);
        }

Open in new window

You can retrieve the selected value on postback with something like:
        protected void Button1_Click(object sender, EventArgs e)
        {
            DropDownList ddl = (this.Form.FindControl("NewDropDown") as DropDownList);
            string id = ddl.UniqueID;

            if (Request.Form[id] != null)
            {
                string value = Request.Form[id].ToString();
            }
        }

Open in new window

0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This video discusses moving either the default database or any database to a new volume.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now