This should help you get started:
Dynamically Adding and Deleting Rows in GridView and Saving All Rows at Once[
^]
The code above is entirely server-side approach. It also uses
ViewState
to hold the data across postbacks. You need to be careful when using
ViewState
to avoid page performance issue. Also
ViewState
has a limit when it comes to size, so make sure that you don't store a huge amount of data in it.
Another approach that you can do is to use JavaScript/jQuery to add dynamic controls at client. That way all interactions only happens at the browser, so you can have a fast response. Just google "adding dynamic textbox using jquery" to get more examples. Here's one I found:
How to add / remove textbox dynamically with jQuery[
^]
Quote:
The user can add an infinte amount of text boxes
You may need to re-think your requirements. You should think about page performance and user experience. What do you think will happen when you add 100,000 TextBox on the page?
Here's a quick example based on your latest comment:
ASPX:
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:TextBox ID="TextBox2" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server" >
</asp:GridView>
CODE BEHIND:
private void BindGrid(int rowcount)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("Name", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("Location", typeof(String)));
if (ViewState["CurrentData"] != null)
{
for (int i = 0; i < rowcount + 1; i++)
{
dt = (DataTable)ViewState["CurrentData"];
if (dt.Rows.Count > 0)
{
dr = dt.NewRow();
dr[0] = dt.Rows[0][0].ToString();
}
}
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr[0] = TextBox1.Text;
dr[1] = TextBox2.Text;
dt.Rows.Add(dr);
}
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
ViewState["CurrentData"] = dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["CurrentData"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentData"];
int count = dt.Rows.Count;
BindGrid(count);
}
else
{
BindGrid(1);
}
TextBox1.Text = string.Empty;
TextBox1.Focus();
}