Search code examples
c#asp.netviewstate

View State not working correctly Asp.Net c#


I have a gridview that has columns for the days of the week. I run this code on the fist load of the page so that the dates are correct.

if (!IsPostBack) {//my public function to set the dates, It works as expected.
    setUpGrid ();
}

Then I have button that when clicked will show the following week 7 days in the future. That all works as well.

Here is the code:

protected void NWeeks_Click(object sender, EventArgs e) {
    DateTime hd2 = Convert.ToDateTime(gvappts.Columns[2].HeaderText);
    if (ViewState["hd2"] == null) {
        ViewState["hd2"] = 0;
    }
    ViewState["hd2"] = ((int) ViewState["hd2"]) + 7;
    gvappts.Columns[2].HeaderText = hd2.AddDays((int) ViewState["hd2"]).ToString(
        "ddd dd MMM", CultureInfo.CreateSpecificCulture("en-US")
    );
}

My problem is, you have to click the button twice before it will fire off the next week calculations. I thought the ViewState would take care of this but not sure where I am going wrong.


Solution

  • I realized after looking at this for a while that since I am dealing with a GridView in order to refresh the HeaderText you also have to DataBind the Gridview. Adding a simple GridviewName.DataBind (); to my function solved my problem.