ASP.NET Webform避免每次Postback加载数据表 [英] ASP.NET Webform avoid loading datatable every Postback
问题描述
我有一个包含GridView,文本框和按钮的WebForm。当我按下按钮时,文本框的数据被添加到GridView。这是我的代码:
I have a WebForm that contain a GridView, a textbox and a button. When i press on the button the data of the text box is added to the GridView. This is my code:
public partial class MyClass : System.Web.UI.Page
{
Static DataTable dt = new DataTable();
DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
dt.Columns.Add("ServiceName", typeof(string));
GridView1.DataSource = dt;
}
GridView1.DataBind();
}
protected void btn_Click(object sender, ImageClickEventArgs e)
{
dr = dt.NewRow();
dr["ServiceName"] = txtBox.Text;
dt.Add(dr);
}
}
问题是我选择让数据表成为静态而不是在每个postBack中重新创建它但由于将静态变量保存在内存中,刷新页面时不清除数据(从此页面创建新对象)并且DataTabledt的数据绑定到gridview在开始..我可以使用什么代替静态变量?
提前感谢
The problem is that I've chosen to make the datatable to be a static not to recreate it in each postBack but as a result of saving the static variable in the memory the data is not cleared when refreshing the page (Create a new object from this page) and the data of the DataTable "dt" is bound to the gridview at the beginning .. what can I use instead of the static variable?
thanks in advance
推荐答案
使用会话
。在Session
中存储DataTable
,并随时检索和修改。
UseSession
. StoreDataTable
inSession
and retrieve and modify whenever you want.
Just避免使用静态。
你可以用它来循环。
Just avoid use of static.
you can use for loop for it.
你好,
在ispostback条件下再次初始化DataTable对象将解决您的问题。
Hi,
Initialize DataTable object again in ispostback condition will solve your problem.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
dt=new DataTable(); // this will make your object null every time you load page.
dt.Columns.Add("ServiceName", typeof(string));
GridView1.DataSource = dt;
}
GridView1.DataBind();
}
这篇关于ASP.NET Webform避免每次Postback加载数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!