How to keep data through postbacks?

Youssef picture Youssef · Sep 12, 2011 · Viewed 18.6k times · Source

I am working on a ASP.NET/C# Website.

I am reading data from a database, saving it in a Dictionary

Dictionary<string, decimal> Results

and then binding it to a ASP.NET chart

PieChart.Series["Series"].Points.DataBind(Results, "Key", "Value", string.Empty);  

I want to change the Label of a Point when I click a button.

protected void Button_Click(object sender, EventArgs e)
{
    PieChart.Series["Series"].Points[0].Label = "abc"
}

But the problem when I click the button, a PostBack happens and the data saved in The "Results" Dictionnary is lost as well as the Chart.

Is there a way to , not lose the data when a postback happens without having to read from the database all over again?

Thank you for any help.

Answer

Pranay Rana picture Pranay Rana · Sep 12, 2011

Yes Make use of ViewState to preserve data between postback.

public Dictionary<string, decimal> Results
{ 
  get { return ViewState["Results"]; }
  set { ViewState["Results"] = value; }
}

Note: Check for the Null value of viewstate otherwise it will throw an Exception or Error