Here's a jQuery example, hope this helps!
Aspx:
<head id="Head1" runat="server"> <title>Controls</title> <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnAdd").click(function () { var field = $("#field").val(); var input = "<input name='parameters' id='field' type='text' />"; var newRow = "<tr><td>" + field + "</td><td>" + input + "</td></tr>"; $('#controls').append(newRow); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <input id="field" type="text" /> <input id="btnAdd" type="button" value="Add" /> <table id="controls" cellpadding="10" cellspacing="10"> </table> <asp:Button ID="btnProcess" runat="server" Text="Process" OnClick="Process" /> </div> </form> </body>
Code for
protected void Process(object sender, EventArgs e) { var parameters = Request.Form["parameters"]; if (parameters != null && parameters.Count() > 0) {
And here is another if you want to do everything on the server. The problem with this approach is that when you add controls dynamically, they disappear in the response message, and you must continue to recreate them in Page_Load , which will add significant processing to your server, I would suggest sticking with the jQuery option
Aspx:
<asp:TextBox ID="txtFieldName" runat="server"></asp:TextBox> <asp:Button ID="btnAddControl" runat="server" Text="Add" OnClick="Add" /> <asp:Table EnableViewState="true" CellPadding="2" CellSpacing="2" BorderWidth="2" BorderStyle="Solid" GridLines="Both" ID="table" runat="server"> <asp:TableHeaderRow> <asp:TableHeaderCell Text="Field" /> <asp:TableHeaderCell Text="Value" /> </asp:TableHeaderRow> </asp:Table> <asp:Button ID="btnPost" runat="server" Text="Post" OnClick="Post" />
Code behind:
public List<string> rows = new List<string>(); protected void Page_Load(object sender, EventArgs e) { if (ViewState["Rows"] != null) { rows = (List<string>)ViewState["Rows"]; if (rows.Count > 0) { foreach (var row in rows) { TextBox textbox = new TextBox(); textbox.Width = 300; table.Rows.Add(GetRow(row,textbox)); } } } } protected void Add(object sender, EventArgs e) { string row = txtFieldName.Text; if (!String.IsNullOrEmpty(row)) { rows.Add(txtFieldName.Text); TextBox textbox = new TextBox(); textbox.Width = 300; table.Rows.Add(GetRow(row, textbox)); ViewState["Rows"] = rows; } } private TableRow GetRow(string text, WebControl txtName) { TableRow tr = new TableRow(); TableCell cell1 = new TableCell(); cell1.Text = text; TableCell cell2 = new TableCell(); cell2.Controls.Add(txtName); tr.Cells.Add(cell1); tr.Cells.Add(cell2); return tr; } protected void Post(object sender, EventArgs e) { if (table.Rows.Count > 0) { System.Diagnostics.Debugger.Break();
source share