Get text from asp:textbox

2019-06-19 23:53发布

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?

4条回答
唯我独甜
2楼-- · 2019-06-20 00:30
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.

查看更多
干净又极端
3楼-- · 2019-06-20 00:37

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

查看更多
Anthone
4楼-- · 2019-06-20 00:54

Try this:

If (!IsPostBack) 
{   
textbox.text = "sometext";
} 
查看更多
贼婆χ
5楼-- · 2019-06-20 00:54

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