Reputation: 3046
When i try to add a new row to the exsisting grid, my values are getting cleared. Using the Viewstate i maintain the Datatable thorought the page and Bind it to the Grid. Think the values are getting cleared during a postback.
// AddNewRow
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int i;
if (dtCurrentTable.Rows.Count > 0)
{
for (i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox txtguide = (TextBox)grdreports.Rows[rowIndex].FindControl("txtAccNo");
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows[i - 1]["txtAccNo"] = txtguide.Text;
rowIndex += 1;
}
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
ViewState["rowcount"] = dtCurrentTable.Rows.Count;
grdreports.DataSource = dtCurrentTable;
grdreports.DataBind();
}
}
// aspx Page:
<asp:GridView ID="grdreports" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
S.No</HeaderTemplate>
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Acc.No/Tel.No">
<ItemTemplate>
<asp:TextBox ID="txtAccNo" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "nvrGuide")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AddNew" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lbtnAddGuide" runat="server" CommandName="Add" Text="Add New"
OnClick="lbtnAddGuide_OnClick"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lbtnDeleteGuide" runat="server" CommandName="Delete" Text="Delete"
OnClick="lbtnDeleteGuide_OnClick"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Where am i going wrong?
Upvotes: 0
Views: 489
Reputation:
My guess is, the names are different.
Which means, The name
`Text='<%#DataBinder.Eval(Container.DataItem, "nvrGuide")%>'`
specified in the .aspx page is "nvrguide" but, the name in the .cs page
TextBox txtguide = (TextBox)grdreports.Rows[rowIndex].FindControl("txtAccNo");
is "txtAccNo". So i think the values you have binded as empty grid in .cs page is different from the .aspx page.
Kindly change it as same in both the pages.
Probably it should throw an error for this. Since the code is not totally shown i cant tel.
Upvotes: 1
Reputation: 1210
For page Postback use following code on page load event
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (GridViewRow row in GridView1.Rows)
{
((TextBox)row.FindControl("txtAccNo")).Text = Request.Form[((TextBox)row.FindControl("txtAccNo")).UniqueID];
}
}
}
Upvotes: 0