Dynamically add and remove TextBox and save value to Database with UserControl using C# and VB.Net in ASP.Net

Last Reply on Apr 20, 2017 07:03 AM By dharmendr

Posted on Apr 18, 2017 04:18 AM

Hi,

I want to add and romove entire row containing two textboxes and save each row data as a single record in sql server database.

I am attaching screenshot of my application and database.

Suppose i click on Add Button

It should generate below output

And when i fill all three row values :

After Click on submit button record should be save like this :

Please help me...!

Thanks

Posted on Apr 20, 2017 07:03 AM Modified on one year ago

Hi Logic24,

Refer the below sample. In the CSNew.aspx.cs page i have written the insert code. To show you i have used datatable and gridview after insert. So you have to ignore the datatable and gridview ie inside the Insert button click event and uncomment the insert method and pass the state and stateid to insert each record to database.

UserControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControl.ascx.cs" Inherits="UserControl" %>
<table>
    <tr>
        <td>
            Enter State
        </td>
        <td>
            State ID
        </td>
        <td>
        </td>
    </tr>
    <tr>
        <td>
            <asp:TextBox ID="txtState" runat="server" />
        </td>
        <td>
            <asp:TextBox ID="txtStateId" runat="server" />
        </td>
        <td>
            <asp:Button ID="btnRemove" runat="server" OnClick="btnRemove_Click" Text="Remove" />
        </td>
    </tr>
</table>

UserControl.ascx.cs

public partial class UserControl : System.Web.UI.UserControl
{
    //Declare the event that we want to raise (we'll handle this in the parent page)
    public event EventHandler RemoveUserControl;

    protected internal void btnRemove_Click(object sender, System.EventArgs e)
    {
        RemoveUserControl(sender, e);
    }
}

CSNew.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CSNew.aspx.cs" Inherits="CSNew" %>

<%@ Register Src="~/UserControl.ascx" TagName="UserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        table
        {
            border: 1px solid #ccc;
        }
        table th
        {
            background-color: #F7F7F7;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 5px;
            border-color: #ccc;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="sm1" runat="server" />
        <asp:UpdatePanel ID="up1" runat="server">
            <ContentTemplate>
                <div class="demo">
                    <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:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" />
        <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" />
    </div>
    </form>
</body>
</html>

CSNew.aspx.cs

public partial class CSNew : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        AddAndRemoveDynamicControls();
    }

    private void AddAndRemoveDynamicControls()
    {
        //Determine which control fired the postback event.  
        Control c = GetPostBackControl(Page);

        if ((c != null))
        {
            //If the add button was clicked, increase the count to let the page know we want to display an additional user control
            if (c.ID.ToString() == "btnAdd")
            {
                ltlCount.Text = (Convert.ToInt16(ltlCount.Text) + 1).ToString();
            }
        }

        //Be sure everything in the placeholder control is cleared out
        ph1.Controls.Clear();

        int ControlID = 0;

        //Since these are dynamic user controls, re-add them every time the page loads.
        for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++)
        {
            UserControl DynamicUserControl = (UserControl)LoadControl("UserControl.ascx");

            //If this particular control id has been deleted from the page, DO NOT use it again.  If we do, it will
            //pick up the viewstate data from the old item that had this control id, instead of generating
            //a completely new control.  Instead, increment the control id so we're guaranteed to get a "new"
            //control that doesn't have any lingering information in the viewstate.            
            while (InDeletedList("uc" + ControlID) == true)
            {
                ControlID += 1;
            }

            //Note that if the item has not been deleted from the page, we DO want it to use the same control id
            //as it used before, so it will automatically maintain the viewstate information of the user control
            //for us.
            DynamicUserControl.ID = "uc" + ControlID;

            //Add an event handler to this control to raise an event when the delete button is clicked
            //on the user control
            DynamicUserControl.RemoveUserControl += this.HandleRemoveUserControl;

            //Finally, add the user control to the panel
            ph1.Controls.Add(DynamicUserControl);

            //Increment the control id for the next round through the loop
            ControlID += 1;
        }
    }

    private bool InDeletedList(string ControlID)
    {
        //Determine if the passed in user control id has been stored in the list of controls that were previously deleted off the page
        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 void HandleRemoveUserControl(object sender, EventArgs e)
    {
        //This handles delete event fired from the user control
        Button remove = (sender as Button);
        //Get the user control that fired this event, and remove it
        UserControl DynamicUserControl = (UserControl)remove.Parent;
        ph1.Controls.Remove((UserControl)remove.Parent);

        //Keep a pipe delimited list of which user controls were removed.  This will increase the 
        //viewstate size if the user keeps removing dynamic controls, but under normal use
        //this is such a small increase in size that it shouldn't be an issue.
        ltlRemoved.Text += DynamicUserControl.ID + "|";

        //Also, now that we've removed a user control decrement the count of total user controls on the page
        ltlCount.Text = (Convert.ToInt16(ltlCount.Text) - 1).ToString();
    }

    protected void btnAdd_Click(object sender, System.EventArgs e)
    {
        //Handled in page load
    }

    protected void btnInsert_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("StateId"), new DataColumn("State") });
        foreach (Control c in ph1.Controls)
        {
            //Find the specific user control that we added to this placeholder, and then get the selected values
            //for the dropdownlist, checkbox, and textbox and print them to the screen.
            if (c.GetType().Name.ToLower() == "usercontrol_ascx")
            {
                UserControl uc = (UserControl)c;
                TextBox tbState = uc.FindControl("txtState") as TextBox;
                TextBox tbStateId = uc.FindControl("txtStateId") as TextBox;
                if (!string.IsNullOrEmpty(tbStateId.Text.Trim()) && !string.IsNullOrEmpty(tbState.Text.Trim()))
                {
                    dt.Rows.Add(tbStateId.Text.Trim(), tbState.Text.Trim());
                    //Insert(tbStateId.Text.Trim(), tbState.Text.Trim());
                }
            }
        }
        gvInsertedRecords.DataSource = dt;
        gvInsertedRecords.DataBind();
    }

    private void Insert(string state, string id)
    {
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "INSERT INTO tblStates VALUES (@StateId, @State)";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@StateId", id);
                cmd.Parameters.AddWithValue("@State", state);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }

    //Find the control that caused the postback.
    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;
    }
}

Screenshot