简体   繁体   中英

How do I maintain data from a datatable after postback?

I created an application that grabs jokes from a database on start and shows the first joke on screen. Now when we hit the Next button it should show the second joke. When I first grab the jokes, I put them in a globally declared datatable. To show the first joke I'm doing:

Title.Value = dt.Rows[0]["joke_title"].ToString();
Detail.Value = dt.Rows[0]["joke_content"].ToString();

Now when I hit Next button I'm running these commands:

Title.Value = dt.Rows[0+1]["joke_title"].ToString();
Detail.Value = dt.Rows[0+1]["joke_content"].ToString();

but when the Next button is hit, the page posts back and I lose the values in datatable. How do I solve the error without losing the data in the datatable?

I put them in a globally declared datatable

Where is this datatable declared? In your page class? Can you show us this code? If it is in your page class, it will not persist across postbacks. The page class is created afresh for each request and it not retain any state.

If you want to maintain state across postbacks, you have to use a state management mechanism like Viewstate / Session in order to be able to maintain the old values of your datatable. You would do this by declaring soemething like:

Session["SomeUniqueKey"] = datatable;

when a page is rendered, all the objects that were created in that page's class are disposed. Now when a post back occurs, the data table wont contain any data. To persist the data across postbacks, you will need to store it somewhere(like InSane said). If the data table contains very few rows, then the best way would be to use Session object.

Once you retrieve the rows from database, store the data table into session:

Session["myTable"] = dt;

At the beginning of PageLoad event handler, check whether its a postback and then, read the data table from session again:

if(this.IsPostBack == true)
{
     DataTable dt = (DataTable)Session["myTable"];
}
else
{
     // fetch the records from database
}

Note that the datatable wont be available across sessions.

You could possibly solve this with a static datatable as well. However, the datatable will then be static across all threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM