简体   繁体   English

回发后如何维护数据表中的数据?

[英]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.现在,当我们点击 Next 按钮时,它应该显示第二个笑话。 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:现在,当我点击 Next 按钮时,我正在运行这些命令:

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.但是当点击 Next 按钮时,页面回发,我丢失了数据表中的值。 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.如果您想在回发之间维护状态,则必须使用像 Viewstate / Session 这样的状态管理机制,以便能够维护数据表的旧值。 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).要在回发中保留数据,您需要将其存储在某处(如 InSane 所说)。 If the data table contains very few rows, then the best way would be to use Session object.如果数据表包含的行很少,那么最好的方法是使用 Session 对象。

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:在 PageLoad 事件处理程序的开始,检查它是否是回发,然后再次从会话中读取数据表:

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.但是,数据表将在所有线程中都是静态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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