Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Question about C# code in Visual Web Developer project

Posted on 2013-05-28
9
Medium Priority
?
424 Views
Last Modified: 2013-05-30
Why is the statement "if (!Page.IsPostBack)" needed in the code below?
 
  protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack)
        {
             string selectedTheme = Page.Theme;
             HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
             
             if (preferredTheme != null)
                 selectedTheme = preferredTheme.Value;

            if (!String.IsNullOrEmpty(selectedTheme) && 
                                                ThemeList.Items.FindByValue(selectedTheme) != null)
                 ThemeList.Items.FindByValue(selectedTheme).Selected = true
        }
    }

This code is an event handler for a ListBox control named ThemeList. ThemeList lists two page style themes: Monochrome and DarkGrey. The theme is stored in a cookie. The user can dynamically switch  between the two themes by choosing either Monochrome or DarkGrey from the list.  The purpose of the event handler is to make sure that the user's choice becomes the selected item in the DropDownList.

I don't understand why if (!Page.IsPostBack) is needed. If I run the program and keep switching between Monochrome and DarkGrey, isn't each change in the dropdownlist's selected value a postback?

The entire VWD project is attached--Planet Wrox.zip.
Planet-Wrox.zip
0
Comment
Question by:MBarongan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 9

Expert Comment

by:sarabhai
ID: 39203531
if (!Page.IsPostBack)

Is used for checking when you come on the page only first time not when postback on the page.
The above code ensure that the code is execute on the page only once. when you revisit the page it will execute again for once.
0
 

Author Comment

by:MBarongan
ID: 39203644
If you remove "if(!Page.IsPostBack)" and then request the page in your browser, nothing happens if you click DarkGrey in the DropDownList. Why is that?
0
 
LVL 9

Expert Comment

by:sarabhai
ID: 39203820
This code is basically to setting your page Theme. If you delete this code then how it is possible to change the page Themes.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 13

Expert Comment

by:Jitendra Patil
ID: 39204151
Hi MBarongan,

To get the difference of your code, you need to keep a debug point on the page_load event
and  ThemeList_SelectedIndexChanged event.

check the cycle that your page events follow you will understand why the above problem happens.

Scenario 1:page_load event with (!page.IsPostBack())
when you run your application it calls your page_load event & in that it checks for (!page.IsPostBack()) and finds the page is post back and does the normal execution as it should.

when you select another Theme it again calls the Page_Load event first in the execution cycle, checks for the page is postback or not and finds that page in not postback then calls ThemeList_SelectedIndexChanged event and executes the code
After executing the  ThemeList_SelectedIndexChanged event code it again calls the Page_Load event and finds the page is postback and executes the code within the if block. but this time the Themlist_SelectindexChanged event has changed the preferred theme is cookie therefore it loads the new theme.

Secenario 2: page_Load Without (!page.IsPostBack())

when you run your application it calls your page_load event & it does the normal execution as it should.

when you select another Theme it again calls the Page_Load event first in the execution cycle, executes the code in page_load event then calls ThemeList_SelectedIndexChanged event and executes the code

After executing the  ThemeList_SelectedIndexChanged event code it again calls the Page_Load event executes the code in page_load event.

so when you check the secenario 2 the Page_load event is called repeatedly and therefore
your page is setting the last theme set in the cookie.

therefore it is necessary to keep the (!Page.IsPostback) in your page_load event.

in short page_load event is called every time when you call any control_events.

Hope this helps.
0
 

Author Comment

by:MBarongan
ID: 39206510
When Response.Redirect(Request.Url.ToString()) executes, it causes another Page_Load. Is that a PostBack or not a PostBack?
0
 
LVL 13

Expert Comment

by:Jitendra Patil
ID: 39206849
it is a postback , that's why you need a check for it.
0
 

Author Comment

by:MBarongan
ID: 39206894
OK, and one last question. When you said "so when you check the scenario 2 the Page_load event is called repeatedly and therefore your page is setting the last theme set in the cookie", why isn't the last theme set in the cookie DarkGrey?  In scenario 2,  when I click DarkGrey, doesn't the ThemeList_SelectedIndexChanged eventhandler send a DarkGrey-cookie to the browser by executing this code:

       preferredTheme.Value = ThemeList.SelectedValue;
       Response.Cookies.Add(preferredTheme);

Then after Response.Redirect(Request.Url.ToString()) executes, doesn't the browser send the DarkGrey-cookie back to the web server, which causes the server to set the new page's theme to DarkGrey  by executing this code:

      HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
      if (preferredTheme != null)
         Page.Theme = preferredTheme.Value;
0
 
LVL 13

Accepted Solution

by:
Jitendra Patil earned 2000 total points
ID: 39207336
in scenario2

even if your ThemeList_SelectedIndexChanged eventhandler executing the code its not able to set the preferred Theme value by the ThemeList.Selected value.

after the above event is executed your code is again calling page_load event as its a postback,so the page_load event code is executed and in the page_load event it is setting the old cookie value back to the ThemeList.

check the code below in your page_load event.

string selectedTheme = Page.Theme;
          HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
          if (preferredTheme != null)
             selectedTheme = preferredTheme.Value;
          if (!String.IsNullOrEmpty(selectedTheme) && ThemeList.Items.FindByValue(selectedTheme) != null)
             ThemeList.Items.FindByValue(selectedTheme).Selected = true;

you are setting the ThemeList.Items.FindByValue(SelectedTheme).Selected=true.

so the above line is changing the Theme selection from client side as per the selection in backend side.

that's why if (!Page.IsPostBack) is necessary for the behaviour you want.

for better understanding try debuggin each and every line of your code with both the secenario's.

Hope this helps.
0
 

Author Closing Comment

by:MBarongan
ID: 39209480
I think I got it now. Thanks for breaking it down in detail. I'll  do line-by-line debug as you suggested to see the order of executions you're talking about.
0

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question