ASP Textbox Not Updated; User Input Not Captured

I was playing with MS SQL just now and I encounter a problem when I would like to update a table in database. It later turned out that the problem was not in my UPDATE statement, but due to the fact that the user inputs in ASP textboxes are “not captured”.

Let me simplify the scenario. I have one textbox and one submit button.

<asp:TextBox ID=”tb_editName” runat=”server” Width=”432px” Text=”<%# retrieveInfo() %>”></asp:TextBox>

<asp:Button ID=”btn_editInfo” runat=”server” Text=”Save” onclick=”btn_editInfo_Click”/>

Here is part of the CodeBehind of the page:

protected void Page_Load(object sender, EventArgs e)
{

DataBind();

}

protected string retrieveInfo()
{

tb_editName.Text = “Kagami”;

}

protected void btn_editInfo_Click(object sender, EventArgs e)
{

//update the table with UPDATE statement

}

If I entered a value, for example “Konata”, into the textbox tb_editName and then clicked the button btn_editInfo, the UPDATE statement will always update the table in database with the value “Kagami”, instead of the user input “Konata”.

I searched on Google and then found the following online discussion: http://forums.asp.net/t/1104590.aspx/1. They said the problem was due to the fact that the Page_Load event would be fired in each postback.

Ah-ha! I found the solution: Using Page.IsPostBack. So basically I just need to make sure my table is updated before the DataBind() is called. Yup, after I have done that, everything is working fine again. =)

What about >=2 Buttons?
The example above has only 1 button. So, will there by any different if we have two or more buttons? The answer is yes.

Page.IsPostBack does not say anything about which button is pressed. So, to handle the cases where we have two or more buttons, we should have a change in the code organization shown above. A detailed discussion can be found here: http://p2p.wrox.com/asp-net-3-5-basics/79502-how-check-if-button-clicked-asp.html. Page_Load should have only the code which needs to be executed every time when the page loads. The actions that need to be carried out after a button is clicked should still be handled in the click event of the button.

Ah… I see.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s