Get text from asp:textbox

2019-06-20 00:00发布

问题:

I am writing ASP.NET project in C#.

The UpdateUserInfo.aspx page consists textboxes and button. In pageLoad() method I set some text to the textbox and when button is cicked I get the new value of textbox and write it into DB.

The problem is even if I have changed the value of textbox textbox.Text() method returns the old value of textbox ("sometext") and write this into DB.

Here the methods:

protected void Page_Load(object sender, EventArgs e)
{
    textbox.text = "sometext";
}

void Btn_Click(Object sender,EventArgs e)
{
    String textbox_text = textbox.text();// this is still equals "somevalue", even I change the textbox value
    writeToDB(textbox_text);
}

So, how to make textbox to appear with somevalue initially, but when user changes this value getText method return the new changed value and write this into DB?

回答1:

protected void Page_Load(object sender, EventArgs e)
{
   if(!Page.IsPostBack)
    {
       textbox.text = "sometext";
    }
}

Postback is setting the textboxs text property back to "somevalue" on button click, you'll want to set the value only once as above.

Postback explained:

In the context of ASP web development, a postback is another name for HTTP POST. In an interactive webpage, the contents of a form are sent to the server for processing some information. Afterwards, the server sends a new page back to the browser.

This is done to verify passwords for logging in, process an on-line order form, or other such tasks that a client computer cannot do on its own. This is not to be confused with refresh or back actions taken by the buttons on the browser.

Source

Reading up on View State will also be helpful in understanding how it all fits together.



回答2:

Try this:

If (!IsPostBack) 
{   
textbox.text = "sometext";
} 


回答3:

Please check Page PostBack in the Page Load Event....



回答4:

Actually on page load textbox is re-initilized

 protected void Page_Load(object sender, EventArgs e)
    {
       if(!Page.IsPostBack)
        {
           textbox.text = "sometext";
        }
    }
    void Btn_Click(Object sender,EventArgs e)
    {
        String textbox_text = textbox.text;
        writeToDB(textbox_text);
    }