0

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?

Guilherme Holtz
  • 474
  • 6
  • 19
Christopher Waugh
  • 441
  • 1
  • 4
  • 15
  • I should mention that there is a very similar question [here](https://stackoverflow.com/questions/5869453/textboxes-lose-value-on-postback), but it was never solved. – Christopher Waugh Mar 14 '18 at 15:59
  • 1
    I guess you overwrite the value in Page_Load. Note that code that is in `Page_Load` executes before this event-handler. You should do initial things like loading from database only `if(!IsPostBack){...}`. – Tim Schmelter Mar 14 '18 at 16:02
  • @TimSchmelter By Jove, you're right! – Christopher Waugh Mar 14 '18 at 16:19

1 Answers1

1

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)
{
    ...
}
Steve Harris
  • 5,014
  • 1
  • 10
  • 25