I have modified my article, to work with Master Pages.
Save (Insert) dynamic TextBox Value (Text) to database in ASP.Net using C# and VB.Net
The only change I did is changed PreInit event to Init event when using Master Pages
HTML
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
input[type=text]
{
margin-bottom: 10pt;
}
</style>
<asp:Panel ID="pnlTextBoxes" runat="server">
</asp:Panel>
<hr />
<asp:Button ID="btnAdd" runat="server" Text="Add New" OnClick="AddTextBox" />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
</asp:Content>
Namespaces
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Code
protected void Page_Init(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
}
protected void AddTextBox(object sender, EventArgs e)
{
int index = pnlTextBoxes.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
private void CreateTextBox(string id)
{
TextBox txt = new TextBox();
txt.ID = id;
pnlTextBoxes.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBoxes.Controls.Add(lt);
}
protected void Save(object sender, EventArgs e)
{
foreach (TextBox textBox in pnlTextBoxes.Controls.OfType<TextBox>())
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Names(Name) VALUES(@Name)"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", textBox.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}