c# gridview不创建新行
本文关键字:新行 创建 gridview | 更新日期: 2023-09-27 18:01:42
我有一个gridview,一个按钮和一个文本框。当在文本框中输入值时,单击按钮,该值应出现在网格视图中。一切都很顺利,直到我插入第二个值。gridview不是创建新行并保留数据,而是刷新页面并在第一个值的位置插入第二个值。
我被告知这与页面加载有关,但我不知道如何阻止这种情况发生。
下面是我的代码:protected void Buton1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Name");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["Name"] = TextBox1.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();
GridView1.DataSource = dt;
GridView1.DataBind();
}
Asp.net是无状态的,所以你必须使用一些状态管理技术来管理控件的状态。如会议
protected void Buton1_Click(object sender, EventArgs e)
{
DataTable dt =null;
if(Session["GridData"]==null)//Initialize a new session only if first time
{
dt= new DataTable();
DataColumn dc = new DataColumn("Name");
dt.Columns.Add(dc);
}
else
{
dt=Session["GridData"] as DataTable;
}
DataRow dr = dt.NewRow();
dr["Name"] = TextBox1.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["GridData"]=dt;//save data in session to retrive in next click
}
试试这个:
private DataTable _dataTable;
protected void Page_Load(object sender, EventArgs e)
{
InitializeTable();
}
private void InitializeTable()
{
if (_dataTable != null) return;
_dataTable = new DataTable();
DataColumn dc = new DataColumn("Name");
_dataTable.Columns.Add(dc);
}
protected void Buton1_Click(object sender, EventArgs e)
{
DataRow dr = _dataTable.NewRow();
dr["Name"] = TextBox1.Text;
_dataTable.Rows.Add(dr);
_dataTable.AcceptChanges();
GridView1.DataSource = _dataTable;
GridView1.DataBind();
}
尝试以下代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
DataTable dt = new DataTable();
ViewState.Add("dt", dt);
}
}
protected void Buton1_Click(object sender, EventArgs e)
{
Datatable dtable = (Datatable)ViewState["dt"];
if (ViewState["dt"] == null)
{
DataColumn dc = new DataColumn("Name");
dtable.Columns.Add(dc);
}
DataRow dr = dtable.NewRow();
dr["Name"] = TextBox1.Text;
dtable.Rows.Add(dr);
dtable.AcceptChanges();
GridView1.DataSource = dtable;
GridView1.DataBind();
ViewState["dt"] = dtable;
}