variables disappear on postback

I have some code that generates a title from a database via Page.Header.Title.  This works fine when the page loads, but the title disappears when I fire a postback event.  Anyone have any suggestions around this issue?
Thanks for reading.

.aspx
<asp:DropDownList AutoPostBack="true" OnSelectedIndexChanged="MainMenuID_SelectedIndexChanged" ID="MainMenuID" runat="server"></asp:DropDownList>
 
.cs
   public string myTitle;
 
   protected void Page_Load(object sender, EventArgs e)
   {
      //myTitle variable is populated from a database...  
      myTitle = "Edit: " + DR["title"].ToString();
      Page.Header.Title = myTitle;
   }	
 
   protected void MainMenuID_SelectedIndexChanged(object sender, EventArgs e)
   {
      //this code populates another menu, but does not touch Page.Header.Title or the myTitle variable
      //This next line populates the title with a blank title...
      Page.Header.Title = myTitle;
   }

Open in new window

cberingerAsked:
Who is Participating?
 
prairiedogConnect With a Mentor Commented:
You will need to save myTitle in a ViewState or Session variable. Upon postback,  myTitle in your code will be redefined and that is why the data is lost.
0
 
jmwheelerCommented:
You should not have to set the title inside MainMenuID_SelectedIndexChanged because Page_Load runs for every postback.

If removing that line doesn't work then post some more code.  I'm assuming DR is a datarow but I don't know how it got a value in the first place.
0
 
jmwheelerCommented:
Actually myTitle should still have a value since it is being set in the Page_Load event every time.
0
 
cberingerAuthor Commented:
I tried a Session variable, but it kept timing out.  This was not desired in my application.  ViewState was perfect.
ViewState["myTitle"] = "Edit: " + DR["title"].ToString();
Page.Header.Title = ViewState["myTitle"].ToString();

Thank you for your help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.