如何在不清除现有数据的情况下添加新的网格行
本文关键字:情况下 添加 网格 数据 清除 | 更新日期: 2023-09-27 18:27:04
My Code在单击按钮时成功地将新行添加到网格视图中,但清除了现有行中所有输入的值。我知道,现有的数据应该存储到ViewState中,但我不知道在哪里/如何实现这一点。
ASPX:
<asp:GridView ID="gvCommissions" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" AutoGenerateDeleteButton="True">
<Columns>
<asp:TemplateField HeaderText="S.NO" ItemStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="lblSno" runat="server" Width="98%"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME" ItemStyle-Width="30%">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Width="98%"></asp:TextBox>
</ItemTemplate>
</Columns>
</asp:GridView>
代码隐藏:
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["gvCommissions"] != null)
dt = (DataTable)ViewState["gvCommissions"];
if (!Page.IsPostBack)
{
GridViewStructure();
AddNewRow();
}
else
{
dt = (DataTable)ViewState["gvCommissions"];
}
ViewState["gvCommissions"] = dt;
}
private void GridViewStructure()
{
dt = new DataTable();
dt.Columns.Add("sno");
dt.Columns.Add("name");
}
private void AddNewRow()
{
dt = new DataTable();
dt.Columns.Add("sno");
dt.Columns.Add("name");
foreach (GridViewRow gvRow in gvCommissions.Rows)
{
DataRow drCurrentRow = dt.NewRow();
drCurrentRow["sno"] = ((Label)gvRow.FindControl("lblSno")).Text;
drCurrentRow["name"] = ((TextBox)gvRow.FindControl("txtName")).Text;
dt.Rows.Add(drCurrentRow);
}
DataRow dr = dt.NewRow();
dr["sno"] = "";
dr["name"] = "";
dt.Rows.Add(dr);
gvCommissions.DataSource = dt;
gvCommissions.DataBind();
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
AddNewRow();
}
它的简单首先检查gridview中是否有行,然后在datatable中添加行值,然后添加空行。如下所示。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
AddNewRow();
}
}
private void AddNewRow()
{
DataTable dt = new DatatTable();
dt.Columns.Add("sno");
dt.Columns.Add("name");
foreach (GridViewRow gvRow in gvCommissions.Rows)
{
DataRow dr = dt.NewRow();
dr["sno"] = ((Label)gvRow.FindControl("lblSno")).Text;
dr["name"] = ((Label)gvRow.FindControl("txtName")).Text;
dt.Rows.Add(dr);
}
DataRow dr1 = dt.NewRow();
dr1["sno"] = "";
dr1["name"] = "";
dt.Rows.Add(dr1);
gvCommissions.DataSource = dt;
gvCommissions.DataBind();
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
AddNewRow();
}
您遗漏了一部分。每次加载页面时,您都将表保存为查看状态,却忘记了使用它!
尝试在页面加载时从视图状态中检索它,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["gvCommissions"] != null) dt = (DataTable)ViewState["gvCommissions"];
if (!Page.IsPostBack)
{
GridViewStructure();
AddNewRow();
}
else
{
dt = (DataTable)ViewState["gvCommissions"];
}
ViewState["gvCommissions"] = dt;
}
我要补充的一点是,将表保存在视图状态不是一个好主意。