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.

<asp:DropDownList AutoPostBack="true" OnSelectedIndexChanged="MainMenuID_SelectedIndexChanged" ID="MainMenuID" runat="server"></asp:DropDownList>
   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

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.
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.
Actually myTitle should still have a value since it is being set in the Page_Load event every time.
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.
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.