Administrateur
Administrateur

Reputation: 901

How to preserve user input in literal control on postback?

On Page_Init, if is post back, I check if a button called Button1 was clicked, if so I add a LiteralControl to a Panel called Panel1:

Panel1.Controls.Add(new LiteralControl("Enter Code:<input type=\"text\" name=\"txtCode\"></td>"));  

As you can see, it is just the text "Enter Code:" followed by a TextBox called txtCode.

I have a second button (Button2) that, when clicked, I would like to retrieve the text entered in txtCode:

protected void Button2_Click(object sender, EventArgs e)
    {
        foreach (Control c in Panel1.Controls)
        {
            if (c is LiteralControl) ...                
        }
    }

I'm not sure how to do this... How can I get the text entered in txtCode?

Upvotes: 1

Views: 1709

Answers (2)

Artyom
Artyom

Reputation: 3571

The generated input doesn't persist its value after turn around (HTTP GET then POST) because it is not System.Web.UI.Control that has ViewState. So the value that user enters is in form collection and you can try to get it from there (Request.Form), but an easier way is to add a TextBox in Init(..). After that a ViewState of the textbox should be loaded on POST and you can access user's input in its Text property.

In Init():

_MyTextBox = new TextBox();
panel1.Controls.Add(_MyTextBox);

In Button_Click:

var value = _MyTextBox.Text ;

Upvotes: 2

Daniel Calliess
Daniel Calliess

Reputation: 853

You can always use the Request.Form collection:

string txtCode = Request.Form["txtCode"];

It will contain all values posted with the current request, regardless of being server side controls or not.

Upvotes: 2

Related Questions