Nurlan
Nurlan

Reputation: 2960

Get text from asp:textbox

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?

Upvotes: 6

Views: 27364

Answers (4)

Rab
Rab

Reputation: 35582

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);
    }

Upvotes: 1

dtsg
dtsg

Reputation: 4459

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.

Upvotes: 16

Vinod
Vinod

Reputation: 4892

Try this:

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

Upvotes: 2

Amol Kolekar
Amol Kolekar

Reputation: 2325

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

Upvotes: 1

Related Questions