我的代码在单击按钮时成功地将新行添加到 gridview,但会清除现有行中的所有输入值。我知道,现有数据应该存储到 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();
}