jpsnow72
jpsnow72

Reputation: 995

Maintaining controls created in code-behind after submit

I have a function that looks like this (simplified):

private void showQuestions()
{
     for (int ansNum = 0; ansNum < 6; ansNum++)
     {
         RadioButton rb = new RadioButton();
         rb.ID = x + letterArray[randomArray[ansNum]].ToString();
         rb.GroupName = "answer" + x;
         rb.Text = char.ToUpper(letterArray[currentCount]) + ". " + dt.Rows[x - 1].ItemArray[2 + randomArray[ansNum]];
         fieldSet.Controls.Add(rb);
     }
}

I call showQuestions() on pageLoad if not IsPostBack. The method actually randomizes the questions from a database and then adds the radio buttons to my fieldset control. The above code is missing much of the guts.

On submit I want these radio buttons to remain on the page, but they are removed. I do not want to have to call showQuestions() again because this would mess the order up and make me hit the database an extra time.

How can I keep them on the page after clicking submit and making other changes?

Upvotes: 0

Views: 165

Answers (1)

KodeKreachor
KodeKreachor

Reputation: 8882

You won't be able to keep dynamically created controls on the page after a post back if you don't call the method to create them each time. You can use an UpdatePanel to accomplish this as well but it's a terribly expensive http call to make which would cause the Page_Load method to be hit on the server anyway.

I'd suggest using an ajax call to post your data. On submit of your form you could call a client side method which a) populated a json object representing your form data, and b) use ajax to post the data to a service method.

Again, the UpdatePanel would work as well, but I tend to avoid it at all costs.

Upvotes: 1

Related Questions