I have a gridview control and I want to input a value to a textbox and click button so that it inserts a value from textbox.text to the gridview. I use this code:
<asp:TextBox ID="txtName" runat="server" ViewStateMode="Enabled"></asp:TextBox>
<br />
<asp:Button ID="btnAddName" runat="server" Text="Button"
onclick="btnAddName_Click" />
<br />
<br />
<asp:GridView ID="gvName" runat="server" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and:
protected void btnAddName_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("lblName", typeof(string)));
DataRow _dr = dt.NewRow();
_dr["lblName"] = txtName.Text;
dt.Rows.Add(_dr);
gvName.DataSource = dt;
gvName.DataBind();
}
I input the text in the textbox and click on the button to insert a value to the gridview. It works ok, but on the second step, after page postback it lost previous data in the gridview.
I want to not lose the previous data in the gridview. Please help me.
You need to add row to original source you are binding to
GridView. if you create new table each time you click button and bind that togridview, it will show data from newDataTableand old data.try this