How to avoid Page_Load() on button click?

Abhishek Ranjan picture Abhishek Ranjan · Mar 28, 2013 · Viewed 43.5k times · Source

I have two buttons, preview and Save. With help of preview button user can view the data based on the format and then can save.

But when preview is clicked, one textbox attached to ajaxcontrol (Calender) becomes empty and user have to fill the date before saving. How to handle this? On preview click i get the details to show the data in layout.

<asp:TextBox ID="txtDate" ReadOnly="true" runat="server"></asp:TextBox>
                    <div style="float: right;">
                        <asp:ImageButton ID="imgcalender1" runat="server" ImageUrl="~/images/calendar.png"
                            ImageAlign="Bottom" />
                        <asp:CalendarExtender ID="ajCal" TargetControlID="txtpublishDate" PopupButtonID="imgcalender1"
                            runat="server">
                        </asp:CalendarExtender>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2"  ValidationGroup="group1" runat="server" ControlToValidate="txtDate"
                            ForeColor="Red" Font-Bold="true" ErrorMessage="*"></asp:RequiredFieldValidator>
                    </div>

<asp:Button ID="btnPreview" runat="server" Text="Preview" OnClick="btnPreview_Click" />
                    <asp:Button ID="btnsubmit" runat="server" ValidationGroup="group1" Text="Save" OnClick="btnsubmit_Click" />

Answer

tgolisch picture tgolisch · Mar 28, 2013

Use Page.IsPostback() in your aspx code (server-side). Like this:

private void Page_Load()
{
    if (!IsPostBack)
    {
        // the code that only needs to run once goes here
    }
}

This code will only run the first time the page is loaded and avoids stepping on user-entered changes to the form.