Hi micah,
Refer below sample.
HTML
UserControl
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControl.ascx.cs" Inherits="UserControl" %>
<table>
<tr>
<td>Item
</td>
<td>Price
</td>
<td>Quantity</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtItem" runat="server" />
</td>
<td>
<asp:TextBox ID="txtPrice" runat="server" />
</td>
<td>
<asp:TextBox ID="txtQuantity" runat="server" />
</td>
</tr>
</table>
Default
<asp:ScriptManager ID="sm1" runat="server" />
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<asp:ListBox ID="lbCategories" CssClass="form-control dual_select" runat="server" multiple=""
AutoPostBack="true" OnSelectedIndexChanged="OnSelectedIndexChanged"></asp:ListBox>
<hr />
<div>
<table>
<tr>
<td>
<asp:PlaceHolder ID="ph1" runat="server" />
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add" />
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Literal ID="ltlCount" runat="server" Text="0" Visible="false" />
<asp:Literal ID="ltlRemoved" runat="server" Visible="false" />
<br />
<br />
<asp:GridView runat="server" ID="gvInsertedRecords" /> <br />
<asp:Button Text="Save" runat="server" OnClick="OnSave" />
Code
protected void Page_Load(object sender, System.EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 4 CategoryID,CategoryName FROM Categories"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
lbCategories.DataSource = cmd.ExecuteReader();
lbCategories.DataValueField = "CategoryID";
lbCategories.DataTextField = "CategoryName";
lbCategories.DataBind();
con.Close();
}
}
}
AddAndRemoveDynamicControls();
}
private void AddAndRemoveDynamicControls()
{
Control c = GetPostBackControl(Page);
if ((c != null) && c.GetType() == typeof(Button))
{
if ((c as Button).Text != "Save")
{
if (c.ID.ToString() == "btnAdd")
{
ltlCount.Text = (Convert.ToInt16(ltlCount.Text) + 1).ToString();
}
}
}
ph1.Controls.Clear();
int ControlID = 0;
for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++)
{
UserControl DynamicUserControl = (UserControl)LoadControl("UserControl.ascx");
while (InDeletedList("uc" + ControlID) == true)
{
ControlID += 1;
}
DynamicUserControl.ID = "uc" + ControlID;
ph1.Controls.Add(DynamicUserControl);
ControlID += 1;
}
}
private bool InDeletedList(string ControlID)
{
string[] DeletedList = ltlRemoved.Text.Split('|');
for (int i = 0; i <= DeletedList.GetLength(0) - 1; i++)
{
if (ControlID.ToLower() == DeletedList[i].ToLower())
{
return true;
}
}
return false;
}
public Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if ((ctrlname != null) & ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
int index = lbCategories.SelectedIndex;
for (int i = 0; i < ph1.Controls.Count; i++)
{
for (int j = 0; j < ph1.Controls[i].Controls.Count; j++)
{
if (ph1.Controls[i].Controls[j].GetType() == typeof(TextBox))
{
if (j == 1)
{
TextBox txt = ph1.Controls[i].Controls[j] as TextBox;
if (string.IsNullOrEmpty(txt.Text))
{
txt.Text = lbCategories.SelectedItem.Text;
return;
}
}
}
}
}
}
protected void OnSave(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Item"), new DataColumn("Price"), new DataColumn("Quantity") });
foreach (Control c in ph1.Controls)
{
if (c.GetType().Name.ToLower() == "usercontrol_ascx")
{
UserControl uc = (UserControl)c;
TextBox tbItem = uc.FindControl("txtItem") as TextBox;
TextBox tbPrice = uc.FindControl("txtPrice") as TextBox;
TextBox tqty = uc.FindControl("txtQuantity") as TextBox;
if (!string.IsNullOrEmpty(tbItem.Text.Trim()) && !string.IsNullOrEmpty(tbPrice.Text.Trim()) && !string.IsNullOrEmpty(tqty.Text.Trim()))
{
dt.Rows.Add(tbItem.Text.Trim(), tbPrice.Text.Trim(), tqty.Text.Trim());
Insert(tbItem.Text.Trim(), tbPrice.Text.Trim(), tqty.Text.Trim());
}
}
}
gvInsertedRecords.DataSource = dt;
gvInsertedRecords.DataBind();
}
private void Insert(string item, string price, string qty)
{
string constr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblStates2 VALUES (@Item, @Price, @Quantity)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Item", item);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@Quantity", qty);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Screenshot
![](https://i.imgur.com/tLq1Oav.gif)