How to preserve user input in literal control on p

2019-08-05 10:54发布

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?

2条回答
再贱就再见
2楼-- · 2019-08-05 11:44

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.

查看更多
Juvenile、少年°
3楼-- · 2019-08-05 11:59

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 ;
查看更多
登录 后发表回答