0

I have a form like the following:

<form id="form1" runat="server">
<div>
    <asp:PlaceHolder ID="plcHolder" runat="server">        
    </asp:PlaceHolder>

    <asp:Button ID="btnSubmit" Text="submit" runat="server" 
        onclick="btnSubmit_Click" />
</div>
</form>

And here is my code:

protected string FetchDataFromDatabase()
{
    return "some long string";
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    { 
        this.plcHolder.Controls.Add(new Label() { Text = FetchDataFromDatabase() } );
    }
}

Page_Load() gets a long string from the database.

protected void btnSubmit_Click(object sender, EventArgs e)
{
    this.plcHolder.Controls.Add(new Label() { Text = "new text" });
}

My Button adds new text to my page. However, when I click the button, I only see the string "new text" but I was looking for both texts ("some long string new text") instead.

I don't want to call my database at every button click since the text already loaded to the page. How do I achieve this?

I know that this example seems a little weird, it's because I tried to give the minimal working example.

Sait
  • 19,045
  • 18
  • 72
  • 99
  • Is `FetchDataFromDatabase()` actually returning a string? – Brad M Apr 12 '13 at 17:25
  • Did you try to put a breakpoint inside the Page.IsPostBack block to make sure it's being executed with no errors? – rivarolle Apr 12 '13 at 17:25
  • @BradM, no, it gets a list of user defined objects. And I'm filling the `place holder` using this data with new controls. – Sait Apr 12 '13 at 17:27
  • See my answer [here](http://stackoverflow.com/questions/8936435/dynamically-added-usercontrol-disappears-when-i-click-on-it/8936436#8936436). Essentially, you must "help" the page preserve its state if you want to avoid repeated trips to the database. – Tim M. Apr 12 '13 at 17:31

1 Answers1

0

In the load, when you get the value from the database, store it in Session:

Session["textFromDatabase"] = GetTextFromDatabase();

and then leverage that value in both places. So if you were in the click you would say:

... Text = Session["textFromDatabase"] + " new text";

and now you can get the value from the database when it's not a post back, just once like you stated, but leverage it over and over.

And I'm pretty sure, based on what you said, this is the inverse of the condition you want, throw a ! in front of it:

if (Page.IsPostBack)
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232