Accessing datatable from different methods
I am creating a web application with back-end on ISeries. In the page load I am populating a datatable and using it as a datasource for my gridview.
What is the best possible way to access the data in the datatable from other methods, on the same page? And in other pages?
The way I do currently is to get data from the gridview and populate in another datatable and then use it... Is there a better (elegant) way to do that? Is st开发者_如何学Pythonoring it in session a good idea??
public partial class Main : System.Web.UI.Page
{
public DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
loadData ld = new loadData();
dt = ld.loadTable();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btn_Click(object sender, EventArgs e)
{
foreach (DataRow row in dt.Rows)
{
// do something
}
}
}
It may not be the best, but you can use Caching in ASP .NET
http://msdn.microsoft.com/en-us/library/6hbbsfk6(v=VS.71).aspx
http://msdn.microsoft.com/en-us/library/18c1wd61(v=VS.71).aspx
http://authors.aspalliance.com/aspxtreme/webapps/aspcachingfeatures.aspx
As Ranhiru says you could use caching, but i'd personally only do this if you really need to. Are you having performance issues which you need to overcome?
If you don't, I'd avoid caching as this will complicate the design of your system. I'd also definitely steer clear of trying to use the same datatable between pages (the only way you'd be able to do this would be to store in Session state. As Kendrick mentioned, you could use ViewState to store the datatable for the life of a page - but I don't think you could pass the datatable from one page to another this way.
I would recommend saving any changes to the database on postback, before redirecting to another page, then in that other page, just read the data from the database again.
You can store it in the ViewState.
OnPageLoad (or Init, depending on what you use it for)
Date In Viewstate?
Load into local variable
else
Create data table in local variable
Save to view state
Now you can access it from anywhere in your page via the local variable.
If you need it in multiple pages you can do all this in a superclass and have your local pages extend that class.
精彩评论