user3561923
user3561923

Reputation:

Why is IsPostBack skipping through my code?

I'm trying to decide using switch case which operation to take where ever section i choose to enter in the page, thus when posting back it will take the right action.

This is the button (Note, this is not the button i'm posting with, rather the one where i enter the section of editing credentials)

<input type="button" value="Edit credentials" onclick="ShowWindow('#EditDetails', 2500); <%WhatToDo = "ChangeUserInfo";%>" />

Code-behind:

public string WhatToDo = "";



protected void Page_Load(object sender, EventArgs e)
{

if (IsPostBack)
    {
        switch (WhatToDo)
        {
            case "ChangeUserInfo": ChangeUserInfo();
            break;
        }
    }

}

protected void ChangeUserInfo(){ something }

The posting seems to work, other than the fact that it doesn't run the switch case... don't know what to do and what am i doing wrong.. If anyone knows what am i doing wrong it'll be great :)

Upvotes: 0

Views: 142

Answers (1)

Liam
Liam

Reputation: 29714

You hook up events in ASP.Net, ASP.Net hides the request and response object for you and wraps it into an Event Driven Architecture . So you don't need to handle the button being pressed in the Page_Load. Instead you need:

Server side button in the .aspx:

<asp:Button runat="server" ID="cmdResubmit" OnClick="cmdAddBooking_Click" Text="Resubmit" />

and an event with the same name as the OnClick in the code behind:

protected void cmdAddBooking_Click(object sender, object e)
{
   //put code button code here
   SomeClass.value = 123;
   SomeClass.StringValue = "1234";
   //etc. etc.
}

notice the name of the method matches: OnClick="cmdAddBooking_Click" in the button!

That's it. If you want multiple buttons then add multiple <asp:Button> with multiple event attached to them.

Note: Clicking a button also triggers a page load (and your event) so any code in the Page_Load event will run on every button click. You can avoid this by wrapping it in if (IsPostBack), this means the code inside this if statement will only run on load not on postback

Upvotes: 1

Related Questions