Click here to Skip to main content
15,845,785 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In the insert statement, I can submit the values of the dynamically generated Textbox to the database.Please help fix it.

What I have tried:

ASPX
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControl.ascx.cs" Inherits="UserControl" %>
<style type="text/css">
    .style1
    {
        width: 131px;
    }
</style>
<table>
    <tr>
        <td>
            Enter State
        </td>
        <td>
            State ID
        </td>
        <td class="style1">
            State Colour</td>
        <td>
        </td>
    </tr>
    <tr>
        <td>
            <asp:TextBox ID="txtState" runat="server" />
        </td>
        <td>
            <asp:TextBox ID="txtStateId" runat="server" />
        </td>
        <td class="style1">
            <asp:TextBox ID="txtStateClr" runat="server" />
        </td>
        <td>
            <asp:Button ID="btnRemove" runat="server" OnClick="btnRemove_Click" Text="Remove" />
        </td>
    </tr>
</table>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControl : System.Web.UI.UserControl
{
    public event EventHandler RemoveUserControl;
    protected internal void btnRemove_Click(object sender, System.EventArgs e)
    {
        RemoveUserControl(sender, e);
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
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 id="Head1" 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>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

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) + 5).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"), new DataColumn("Statecolour") });
        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;
                TextBox tbStateClr= uc.FindControl("txtStateClr") as TextBox;
                if (!string.IsNullOrEmpty(tbStateId.Text.Trim()) && !string.IsNullOrEmpty(tbState.Text.Trim()) && !string.IsNullOrEmpty(tbStateClr.Text.Trim()))
                {
                    dt.Rows.Add(tbStateId.Text.Trim(), tbState.Text.Trim(),tbStateClr.Text.Trim());
                    //Insert(tbStateId.Text.Trim(), tbState.Text.Trim());
                }
            }
        }
        gvInsertedRecords.DataSource = dt;
        gvInsertedRecords.DataBind();
    }

    private void Insert(string state, string id, string Statecolour)
    {
       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;
    }
}
Posted
Updated 14-Jan-21 3:38am
v5
Comments
Richard MacCutchan 11-Jan-21 9:21am    
You should ask the person who write it. No one here is likely to go to that website.
Gerry Schmitz 11-Jan-21 10:38am    
An idea gone wrong. Simply hiding / collapsing and showing would have made life simpler.
Member 11307750 11-Jan-21 10:57am    
why not help with the code
Richard MacCutchan 12-Jan-21 12:28pm    
Why not explain what the problem is?

 
Share this answer
 
v2
protected void btnInsert_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("StateId"), new DataColumn("State"), new DataColumn("Statecolour") });
        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;
                TextBox tbStateClr= uc.FindControl("txtStateClr") as TextBox;
                if (!string.IsNullOrEmpty(tbStateId.Text.Trim()) && !string.IsNullOrEmpty(tbState.Text.Trim()) && !string.IsNullOrEmpty(tbStateClr.Text.Trim()))
                {
                    dt.Rows.Add(tbStateId.Text.Trim(), tbState.Text.Trim(),tbStateClr.Text.Trim());
                   Insert(tbStateId.Text.Trim(), tbState.Text.Trim(),tbStateClr.Text.Trim());
                   // THE INSERT STATEMENT ABOVE  WAS NOT ENABLED BEFORE
                }
            }
        }
        gvInsertedRecords.DataSource = dt;
        gvInsertedRecords.DataBind();
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900