Search code examples
c#asp.netwebformsviewstate

Asp textbox clear on click


I have some ASP textboxes I want to fill out.

<div class="form-group">
    <asp:Label CssClass="form-control-label" ID="LFirstName" Text="First Name"
        AssociatedControlID="TBFirstName" runat="server"></asp:Label>
    <asp:TextBox CssClass="form-control" ID="TBFirstName" 
        runat="server" MaxLength="50"></asp:TextBox>

    <asp:Label CssClass="form-control-label" ID="LLastName" Text="Last Name" 
        AssociatedControlID="TBLastName" runat="server"></asp:Label>
    <asp:TextBox CssClass="form-control" ID="TBLastName" 
        runat="server" MaxLength="50"></asp:TextBox>
    ...
</div>

When a button is pushed...

<asp:Button ID="BTN_UserSubmit" runat="server" 
    Text="Submit" OnClick="Click_UserSubmit"/>

I have some magical things I want to do with them

protected void Click_UserSubmit(object sender, EventArgs e)
{
    Log("TBFistName" + TBFirstName.Text);
    Log("TBLastName" + TBLastName.Text);
    ...

Unfortunately, my log shows nothing but empty strings:

TBFistName 
TBLastName 

Why does this happen, and how can I keep the values long enough to do anything with them?


Solution

  • You are probably initialising/clearing the values in Page_Load.

    Whenever you postback, either by a button click or some other means, the Page_Load method will be called before the click event.

    So you need to put any initialisation logic inside:

    if (!Page.IsPostback)
    {
        ...
    }