locked
Dynamic Generation of Text Fields and Saving the Values to database RRS feed

  • Question

  • User-190697402 posted

    Hi,

    I have to dynamically generate three textfields placed inside a panel.This text fields are displayed only when the approval column of three approvers are checked .

    If any of the approver is not checked then the panel wont be displaying.

    I want to dynamically generate the textfileds on a button click and want to save the data to the database.

    Appreciate help on this.

    This is the aspx code for panel.

    <asp:Panel ID="pnlPartnerDetails" runat="server">
                                        <!--Partners Name-->
                                        <tr>
                                            <td class="auto-style9" style="text-align:left;">Partners Name</td>
                                            <td class="auto-style12">
                                                <asp:TextBox ID="txtPartnerName" ValidationGroup="editCustomer"  runat="server"></asp:TextBox>                                    
                                            </td>
                                            <td style="text-align:left;">
                                                <asp:ImageButton ID="imgBtnSalesChannelHead" ImageUrl="~/images/plus.png"  runat="server"/>
                                            </td>
                                            <td style="text-align:left;">                                    
                                            </td>
                                        </tr>
    
                                        <!--Partners Email-->
                                        <tr>
                                            <td class="auto-style9" style="text-align:left;">Partners Email</td>
                                            <td class="auto-style12">
                                                <asp:TextBox ID="txtPartnerEmail" ValidationGroup="editCustomer"  runat="server"></asp:TextBox>                                    
                                            </td>
                                            <td></td>
                                            <td style="text-align:left;">                                    
                                            </td>
                                        </tr>
    
                                        <!--Partners Designation-->
                                        <tr>
                                            <td class="auto-style9" style="text-align:left;">Partners Designation</td>
                                            <td class="auto-style12">
                                                <asp:TextBox ID="txtPartnersDesignation" ValidationGroup="editCustomer"  runat="server"></asp:TextBox>                                    
                                            </td>
                                            <td></td>
                                            <td style="text-align:left;">                                    
                                            </td>
                                        </tr>
                                    </asp:Panel>

    Wednesday, July 15, 2020 2:10 AM

Answers

  • User348806598 posted

    the previously entered details are removed.

    As subsequent postback data gets lost for a dynamic control. You need to retain data (in session) while adding new control-

            protected void btnAddAnother_Click(object sender, EventArgs e)
            {
                Dictionary<int, PertnerData> numberOfControls = (Dictionary<int, PertnerData>)Session["ControlGenerated"];
                numberOfControls.Add(numberOfControls.Keys.Max() + 1, new PertnerData());
                fillData(ref numberOfControls);
                Session["ControlGenerated"] = numberOfControls;
                GenerateControls();
            }
    
            private void fillData(ref Dictionary<int, PertnerData>  numberOfControls) {
    
                foreach (var controls in numberOfControls) {
                    controls.Value.PName = GetValue($"txtPName{controls.Key}");
                    controls.Value.PEmail = GetValue($"txtPEmail{controls.Key}");
                    controls.Value.PDesignation = GetValue($"txtPDesignation{controls.Key}"); 
                }
            }
    
            string GetValue(string id)
            {
                return ((TextBox)container.FindControl(id))?.Text;
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 20, 2020 6:08 PM

All replies

  • User-939850651 posted

    Hi teenajohn1989,

    You could use the Visible property of the panel to control whether it is displayed on the page.

    And what is the approver you mentioned, is it CheckBox? If this is the case, you could determine and set whether the panel is displayed in the OnCheckedChanged event.

    If you want to dynamically generate controls, you could choose where to place them, use something like:

    Page.FindControl(position).Controls.Add(control);

    Or you could define the control in advance and then use the display panel method to display it.

    For more details, please refer to the following code:

    Page code:
    
    <body>
        <form id="form1" runat="server">
            <asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true"/>:approver1<br />
            <asp:CheckBox ID="CheckBox2" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true"/>:approver2<br />
            <asp:CheckBox ID="CheckBox3" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true"/>:approver3<br />
            <div>
                <asp:Panel ID="pnlPartnerDetails" runat="server" Visible="false">
                    <table>
                        <!--Partners Name-->
                        <tr>
                            <td class="auto-style9" style="text-align: left;">Partners Name</td>
                            <td class="auto-style12">
                                <asp:TextBox ID="txtPartnerName" ValidationGroup="editCustomer" runat="server"></asp:TextBox>
                            </td>
                            <td style="text-align: left;">
                                <asp:ImageButton ID="imgBtnSalesChannelHead" ImageUrl="~/images/plus.png" runat="server" OnClick="imgBtnSalesChannelHead_Click"/>
                            </td>
                            <td style="text-align: left;" runat="server" id="TextField1"></td>
                        </tr>
    
                        <!--Partners Email-->
                        <tr>
                            <td class="auto-style9" style="text-align: left;">Partners Email</td>
                            <td class="auto-style12">
                                <asp:TextBox ID="txtPartnerEmail" ValidationGroup="editCustomer" runat="server"></asp:TextBox>
                            </td>
                            <td></td>
                            <td style="text-align: left;"></td>
                        </tr>
    
                        <!--Partners Designation-->
                        <tr>
                            <td class="auto-style9" style="text-align: left;">Partners Designation</td>
                            <td class="auto-style12">
                                <asp:TextBox ID="txtPartnersDesignation" ValidationGroup="editCustomer" runat="server"></asp:TextBox>
                            </td>
                            <td></td>
                            <td style="text-align: left;"></td>
                        </tr>
                    </table>
                </asp:Panel>
            </div>
        </form>
    </body>
    Code behind:
    
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
            {
                if (CheckBox1.Checked && CheckBox2.Checked && CheckBox3.Checked)
                {
                    pnlPartnerDetails.Visible = true;
                }
                else
                {
                    pnlPartnerDetails.Visible = false;
                }
            }
    
            protected void imgBtnSalesChannelHead_Click(object sender, ImageClickEventArgs e)
            {
                //save data to database
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString()))
                {
                    ......
                }
                //generate the TextBox
                TextBox box = new TextBox();
                box.Attributes.Add("ID", "text1");
                Page.FindControl("TextField1").Controls.Add(box);
            }

    Result:

    If I misunderstood what you meant, please let me know.

    Hope this can help you.

    Best regards,

    Xudong Peng

    Wednesday, July 15, 2020 3:49 AM
  • User-190697402 posted

    Hi XuDong Peng,

    Thanks for your reply.

    I managed to display the textfields based on the approval.What i need is , i want to create three textfields on a single click.

    that means replicating  all the three textfields inside the panel.

    i want to generate as many textfields,not just one .

    Hope it is clear.Thanks in advance.

    Wednesday, July 15, 2020 2:34 PM
  • User348806598 posted

    you can simply try-

    var panel = Page.FindControl("TextField1");
    int numberOfTextBox = 5;
    for(int i =0; i<numberOfTextBox; i++)
    {
        TextBox box = new TextBox();
        box.Attributes.Add("ID", $"text{i}");
        panel.Controls.Add(box);
    }
    Wednesday, July 15, 2020 2:45 PM
  • User-190697402 posted

    Hi asteranup,

    I cannot hardcode the no:of textbox,if the user wants to add more than 5 textboxes ,then this wont work.

    and also i want to generate the entire textboxes inside the panel,which means when i click on the add button it should generate the three textboxes - Partner Name,Partner Email,Partner Designation.

    Thanks in advance

    Wednesday, July 15, 2020 3:15 PM
  • User348806598 posted

    You don't need to hard code number to 5. That's why I have added it as a variable. You can get a number of textboxes from any sources. I believe you need a set of three text boxes and you need to set to be dynamic. Logic follows the same process-

    You can check working code here-

    https://github.com/anupdg/dotnetsamples/blob/master/WebFormSamples/WebFormSamples/2169001-Dynamic%2BGeneration%2Bof%2BText%2BFields%2Band%2BSaving%2Bthe%2BValues%2Bto%2Bdatabase.aspx.cs

    Wednesday, July 15, 2020 7:11 PM
  • User-190697402 posted

    Hi asteranup,

    Thanks for your response.

    I tried your code.It works !But my requirement is different.

    Please check this screenshot

    There wont be any sources to get the no:of textboxes to be generated. When i click on the plus button it has to generate the next set.

    Hope this is clear.

    Thursday, July 16, 2020 8:14 AM
  • User348806598 posted

    It should be similar, instead of looping through and creating control, you need to add a set of controls on the click of a button. You can use the same List<YourDataClass> to hold all the dynamically added controls. Remember to add regenerate the controls from init as dynamically created control will live through every postback

    Thursday, July 16, 2020 9:06 AM
  • User-190697402 posted

    Hi asteranup,

    Im didnt get what you are saying.Could you please explain a bit more,i'm new to this technology.

    protected void btnGenerateControls_Click(object sender, EventArgs e)
            {
                container.Controls.Clear();
                Session["ControlGenerated"] = Convert.ToInt32(txtNimberOfGroup.Text);
                GenerateControls();
            }

    How i can set this txtNimberOfGroup.Text value.Because this value is using for the loop.

    Thanks in advance!

    Thursday, July 16, 2020 9:56 AM
  • User-190697402 posted

    Hi asteranup,

    I tried out ,when i click on the add button,the whole content is gone and its dispalying empty page.

    Here is my code,i made some changes.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication6.WebForm1" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Panel ID="pnlPartnerDetails" runat="server">
                    <table>
                                        <!--Partners Name-->
                                        <tr>
                                            <td class="auto-style9" style="text-align:left;">Partners Name</td>
                                            <td class="auto-style12">
                                                <asp:TextBox ID="txtPName" ValidationGroup="editCustomer"  runat="server"></asp:TextBox>                                    
                                            </td>
                                            <td style="text-align:left;">
                                                <asp:ImageButton ID="imgBtnSalesChannelHead" ImageUrl="~/images/plus.png" OnClick="imgBtnSalesChannelHead_Click"  runat="server"/>
                                            </td>
                                            <td style="text-align:left;">                                    
                                            </td>
                                        </tr>
    
                                        <!--Partners Email-->
                                        <tr>
                                            <td class="auto-style9" style="text-align:left;">Partners Email</td>
                                            <td class="auto-style12">
                                                <asp:TextBox ID="txtPEmail" ValidationGroup="editCustomer"  runat="server"></asp:TextBox>                                    
                                            </td>
                                            <td></td>
                                            <td style="text-align:left;">                                    
                                            </td>
                                        </tr>
    
                                        <!--Partners Designation-->
                                        <tr>
                                            <td class="auto-style9" style="text-align:left;">Partners Designation</td>
                                            <td class="auto-style12">
                                                <asp:TextBox ID="txtPDesignation" ValidationGroup="editCustomer"  runat="server"></asp:TextBox>                                    
                                            </td>
                                            <td></td>
                                            <td style="text-align:left;">                                    
                                            </td>
                                        </tr>
    </table> </asp:Panel> </div> </form> </body> </html>

    Here is my aspx.cs file

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication6
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            class PertnerData
            {
                public string PName { get; set; }
                public string PEmail { get; set; }
                public string PDesignation { get; set; }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
            private void AddLabel(string label, Panel p)
            {
                Label lbl = new Label();
                lbl.Text = label;
                p.Controls.Add(lbl);
            }
            private void AddTextBox(string id, Panel p)
            {
                TextBox box = new TextBox();
                box.ID = id;
                p.Controls.Add(box);
            }
    
            protected void Page_PreInit(object sender, EventArgs e)
            {
                if (Page.IsPostBack)
                {
                    GenerateControls();
                }
            }
    
            private void GenerateControls()
            {
                int numberOfControls = Convert.ToInt32(Session["ControlGenerated"]);
                pnlPartnerDetails.Controls.Clear();
                for (int i = 0; i < numberOfControls; i++)
                {
                    Panel p = new Panel();
                    p.Style.Add("border", "solid 1px blue");
                    p.Style.Add("margin", "5px");
                    pnlPartnerDetails.Controls.Add(p);
    
                    AddLabel($"Name {i}", p);
                    AddTextBox($"txtPName{i}", p);
                    AddLabel($"Email {i}", p);
                    AddTextBox($"txtPEmail{i}", p);
                    AddLabel($"Designation {i}", p);
                    AddTextBox($"txtPDesignation{i}", p);
                    pnlPartnerDetails.Controls.Add(new LiteralControl("<br />"));
                }
    
            }
            protected void imgBtnSalesChannelHead_Click(object sender, ImageClickEventArgs e)
            {
                int numberOfControls = Convert.ToInt32(Session["ControlGenerated"]);
                numberOfControls++;
                Session["ControlGenerated"] = numberOfControls;
                GenerateControls();
            }
    
            protected void btnGetValues_Click(object sender, EventArgs e)
            {
                int numberOfControls = Convert.ToInt32(Session["ControlGenerated"]);
    
                List<PertnerData> data = new List<PertnerData>();
    
                PertnerData pd;
                for (int i = 0; i < numberOfControls; i++)
                {
                    pd = new PertnerData();
                    pd.PName = GetValue($"txtPName{i}");
                    pd.PEmail = GetValue($"txtPEmail{i}");
                    pd.PDesignation = GetValue($"txtPDesignation{i}");
                    data.Add(pd);
                }
            }
            string GetValue(string id)
            {
                return ((TextBox)pnlPartnerDetails.FindControl(id)).Text;
            }
    
        }
    }

    Couldnt figure out why its displaying a blank page on button click.

    Thursday, July 16, 2020 11:23 AM
  • User348806598 posted

    The code I have shared is the working code. You can run my application by cloning from git. I want to believe that you can copy the code and make the necessary changes to add to your project.

    Thursday, July 16, 2020 12:05 PM
  • User-190697402 posted

    Hi asteranup,

    I managed to get it done.

    i have few doubts ,

    1)Whenever i change the for loop intialisation value to 1,the fields are not generating on the first click.When i click for the second time fields are generating.

    Webform1.aspx

    Webform1.aspx.cs

    2)how can i remove the control dynamically? Please see this screenshot

    Thanks in advance

    Friday, July 17, 2020 4:41 AM
  • User348806598 posted

    Hi,

    I have already shared a working code. Please clone the repo to your local, run and debug, you can easily find out what you are missing.

    https://github.com/anupdg/dotnetsamples/blob/master/WebFormSamples/WebFormSamples/2169001-Dynamic%2BGeneration%2Bof%2BText%2BFields%2Band%2BSaving%2Bthe%2BValues%2Bto%2Bdatabase1.aspx.cs

    Friday, July 17, 2020 4:52 AM
  • User-190697402 posted

    Hi asteranup,

    Yes,your code is working.

    i had made the changes by editing your working code only,my doubt is 

    private void GenerateControls()
    {
    int numberOfControls = Convert.ToInt32(Session["ControlGenerated"]);
    container.Controls.Clear();
    for (int i = 1; i < numberOfControls; i++)
    {
    }
    }

    in this for loop i have changed the value of int i=1,clicking for first time it wont generate the textfields,but when i click for the second time it will generate.

    if i revert my change that is int i = 0,everything works fine.first click itself it will generate the textfileds with id 0.

    and in your code ,the page first load with only Addnew and Getvalues link.

    So i have changed it to my requirement.In my page at first it will have a panel with three textfields .then i click on the button it will add another panel.This is exactly what i need.

    and in your code there is no option to remove the controls. thats what i asked as my second doubt.

    Thanks for your kind and quick responses

    Friday, July 17, 2020 6:01 AM
  • User348806598 posted

    Don't change the index. Instead of that add the following code-

            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack) {
                    Session["ControlGenerated"] = 1;
                    GenerateControls();
                }
            }
    Friday, July 17, 2020 6:31 AM
  • User-190697402 posted

    Hi asteranup,

    Thank you so much :) . Finally i got it done. :)

    One more help i need,for deleting the dynamic text field generated i have wriiten the following code

    private void RemoveControls()
            {
                int numberOfControls = Convert.ToInt32(Session["ControlGenerated"]);
                container.Controls.Clear();
                for (int i = 1; i < (numberOfControls - 1); i++)
                {
                    Panel p = new Panel();
                    p.Controls.Remove(new LiteralControl($"<tr id='partnerName{i}'>"));
    
                }
    
    
            }

    protected void imageButton_Click(object sender, ImageClickEventArgs e)
            {
                int numberOfControls = Convert.ToInt32(Session["ControlGenerated"]);
                numberOfControls--;
                Session["ControlGenerated"] = numberOfControls;
                RemoveControls();
    
            }



    But when i click on the remove button.its deleting the entire textfields generated dynamically.

    Could you please help me to figure out the issue?

    Friday, July 17, 2020 7:57 AM
  • User-939850651 posted

    Hi teenajhn1989,

    According to your description above, I created a simple example to meet your needs.

    For more details, please refer to the following code:

    Page code:
    
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.4.1.min.js"></script>
        <script>
            function DeleteRows() {
                $('<%="#"+hf_deleteCommand.ClientID%>').val("DeleteRow");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div runat="server" id="mainDiv">
                <asp:Panel ID="pnlPartnerDetails" runat="server">
                    <table>
                        <!--Partners Name-->
                        <tr>
                            <td class="auto-style9" style="text-align: left;">Partners Name</td>
                            <td class="auto-style12">
                                <asp:TextBox ID="txtPartnerName" ValidationGroup="editCustomer" runat="server"></asp:TextBox>
                            </td>
                            <td style="text-align: left;">
                                <asp:ImageButton ID="imgBtnSalesChannelHead" ImageUrl="~/images/plus.png" runat="server" OnClick="imgBtnSalesChannelHead_Click" />
                            </td>
                            <td style="text-align: left;" runat="server" id="TextField1"></td>
                        </tr>
    
                        <!--Partners Email-->
                        <tr>
                            <td class="auto-style9" style="text-align: left;">Partners Email</td>
                            <td class="auto-style12">
                                <asp:TextBox ID="txtPartnerEmail" ValidationGroup="editCustomer" runat="server"></asp:TextBox>
                            </td>
                            <td></td>
                            <td style="text-align: left;"></td>
                        </tr>
    
                        <!--Partners Designation-->
                        <tr>
                            <td class="auto-style9" style="text-align: left;">Partners Designation</td>
                            <td class="auto-style12">
                                <asp:TextBox ID="txtPartnersDesignation" ValidationGroup="editCustomer" runat="server"></asp:TextBox>
                            </td>
                            <td></td>
                            <td style="text-align: left;"></td>
                        </tr>
                    </table>
                </asp:Panel>
                <asp:HiddenField ID="hf_deleteCommand" runat="server" />
            </div>
        </form>
    </body>
    Code behind:
    
    public static int controlNum;
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    controlNum = 0;
                }
    
                if (IsPostBack)
                {
                    if(hf_deleteCommand.Value == "DeleteRow")
                    {
                        controlNum--;
                        hf_deleteCommand.Value = "";
                        GenerateControl();
                    }
                }
    
            }
    
            private void AddLabel(string label, Panel p)
            {
                Label lbl = new Label();
                lbl.Text = label;
                p.Controls.Add(lbl);
            }
            private void AddTextBox(string id, Panel p)
            {
                TextBox box = new TextBox();
                box.ID = id;
                p.Controls.Add(box);
            }
    
            protected void imgBtnSalesChannelHead_Click(object sender, ImageClickEventArgs e)
            {
                controlNum++;
                GenerateControl();
            }
    
            private void GenerateControl() {
                for (int i = 0; i < controlNum; i++)
                {
                    Panel p = new Panel();
                    p.ID = $"panel{i}";
                    p.Style.Add("border", "solid 1px blue");
                    p.Style.Add("margin", "5px");
                    mainDiv.Controls.Add(p);
    
                    AddLabel($"Name {i}:", p);
                    AddTextBox($"txtPName{i}", p);
                    
                    AddLabel($"Email {i}:", p);
                    AddTextBox($"txtPEmail{i}:", p);
    
                    AddLabel($"Designation {i}:", p);
                    AddTextBox($"txtPDesignation{i}", p);
    
                    Button btn = new Button();
                    btn.Text = "Delete";
                    btn.OnClientClick = "DeleteRows()";
    
                    p.Controls.Add(btn);
                    mainDiv.Controls.Add(new LiteralControl("<br />"));
                }
            }

    Result:

    Best regards,

    Xudong Peng

    Friday, July 17, 2020 9:34 AM
  • User-190697402 posted

    Hi XuDong Peng,

    Thanks for your reply .

    In your demo,its not deleting the correct index.

    when you click delete button for the second row,its deleting third row.

    and i want to implement this without using jquery .

    Thanks again for your quick response .

    Friday, July 17, 2020 9:49 AM
  • User348806598 posted

    You can add link button also as a part of each rows. Done some changes on the existing code you can check below-

    https://github.com/anupdg/dotnetsamples/blob/master/WebFormSamples/WebFormSamples/2169001-Dynamic%2BGeneration%2Bof%2BText%2BFields%2Band%2BSaving%2Bthe%2BValues%2Bto%2Bdatabase1.aspx.cs

        public partial class _2169001_Dynamic_Generation_of_Text_Fields_and_Saving_the_Values_to_database1 : System.Web.UI.Page
        {
            class PertnerData
            {
                public string PName { get; set; }
                public string PEmail { get; set; }
                public string PDesignation { get; set; }
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack) {
                    Session["ControlGenerated"] = new Dictionary<int, PertnerData> { { 1, new PertnerData() } };
                    GenerateControls();
                }
            }
            private void AddLabel(string label, Panel p)
            {
                Label lbl = new Label();
                lbl.Text = label;
                p.Controls.Add(lbl);
            }
            private void AddTextBox(string id, Panel p, string data)
            {
                TextBox box = new TextBox();
                box.ID = id;
                box.Text = data;
                p.Controls.Add(box);
            }
    
            protected void Page_PreInit(object sender, EventArgs e)
            {
                if (Page.IsPostBack)
                {
                    GenerateControls();
                }
            }
    
            private void GenerateControls()
            {
                Dictionary<int, PertnerData> numberOfControls = (Dictionary<int, PertnerData>)Session["ControlGenerated"];
                container.Controls.Clear();
                foreach (var i in numberOfControls)
                {
                    Panel p = new Panel();
                    p.ID = $"container{i.Key}";
                    p.Style.Add("border", "solid 1px blue");
                    p.Style.Add("margin", "5px");
                    container.Controls.Add(p);
    
                    AddLabel($"Name {i.Key}", p);
                    AddTextBox($"txtPName{i.Key}", p, i.Value.PName);
                    AddLabel($"Email {i.Key}", p);
                    AddTextBox($"txtPEmail{i.Key}", p, i.Value.PEmail);
                    AddLabel($"Designation {i.Key}", p);
                    AddTextBox($"txtPDesignation{i.Key}", p, i.Value.PDesignation);
                    AddDeleteButton(i.Key, p);
                    container.Controls.Add(new LiteralControl("<br />"));
                }
            }
    
            private void AddDeleteButton(int id, Panel p)
            {
                LinkButton button = new LinkButton();
                button.ID = $"Delete{id}";
                button.Attributes.Add("DataId", id.ToString());
                button.Text = $"Delete {id}";
                button.Style.Add("margin-left", "5px");
                button.Click += new EventHandler(delete_Click);
                p.Controls.Add(button);
            }
            protected void delete_Click(object sender, EventArgs e) {
                var btn = sender as LinkButton;
                var idToDelete = Convert.ToInt32( btn.Attributes["DataId"]);
                Dictionary<int, PertnerData> numberOfControls = (Dictionary<int, PertnerData>)Session["ControlGenerated"];
                numberOfControls = numberOfControls.Where(c => c.Key != idToDelete).ToDictionary(x => x.Key, x => x.Value);
                Session["ControlGenerated"] = numberOfControls;
                GenerateControls();
            }
    
            protected void btnAddAnother_Click(object sender, EventArgs e)
            {
                Dictionary<int, PertnerData> numberOfControls = (Dictionary<int, PertnerData>)Session["ControlGenerated"];
                numberOfControls.Add(numberOfControls.Keys.Max() + 1, new PertnerData());
                Session["ControlGenerated"] = numberOfControls;
                GenerateControls();
            }
    
            protected void btnGetValues_Click(object sender, EventArgs e)
            {
                var keys = ((Dictionary<int, PertnerData>)Session["ControlGenerated"]).Keys;
    
                Dictionary<int, PertnerData> numberOfControls = new Dictionary<int, PertnerData>();
                PertnerData pd;
                foreach (var i in keys)
                {
                    pd = new PertnerData();
                    pd.PName = GetValue($"txtPName{i}");
                    pd.PEmail = GetValue($"txtPEmail{i}");
                    pd.PDesignation = GetValue($"txtPDesignation{i}");
                    numberOfControls[i] = pd;
                }
                Session["ControlGenerated"] = numberOfControls;
            }
            string GetValue(string id)
            {
                return ((TextBox)container.FindControl(id)).Text;
            }
        }
    Friday, July 17, 2020 11:12 AM
  • User-190697402 posted

    Hi asteranup,

    Thanks for your reply.The delete button is working fine.

    But i have one more issue,when the page loads,it loads with the generated textfields with deletebutton,even if i didnt click the add new button.

    Please see this screenshot

    And whenever i add details in the textfields and click the add new button ,the previously entered details are removed.

    my sincere thanks for your effort.

    Saturday, July 18, 2020 4:28 PM
  • User-190697402 posted

    Hi astreanup,

    Could you please help me to  resolve this -  whenever i add details in the textfields and click the add new button ,the previously entered details are removed.

    Thanks in advance

    Monday, July 20, 2020 7:11 AM
  • User348806598 posted

    But i have one more issue,when the page loads,it loads with the generated textfields with deletebutton,even if i didnt click the add new button.

    Change -

    Session["ControlGenerated"] = new Dictionary<int, PertnerData> { { 1, new PertnerData() } };

    to-

    Session["ControlGenerated"] = new Dictionary<int, PertnerData> {  } };
    Monday, July 20, 2020 5:41 PM
  • User348806598 posted

    the previously entered details are removed.

    As subsequent postback data gets lost for a dynamic control. You need to retain data (in session) while adding new control-

            protected void btnAddAnother_Click(object sender, EventArgs e)
            {
                Dictionary<int, PertnerData> numberOfControls = (Dictionary<int, PertnerData>)Session["ControlGenerated"];
                numberOfControls.Add(numberOfControls.Keys.Max() + 1, new PertnerData());
                fillData(ref numberOfControls);
                Session["ControlGenerated"] = numberOfControls;
                GenerateControls();
            }
    
            private void fillData(ref Dictionary<int, PertnerData>  numberOfControls) {
    
                foreach (var controls in numberOfControls) {
                    controls.Value.PName = GetValue($"txtPName{controls.Key}");
                    controls.Value.PEmail = GetValue($"txtPEmail{controls.Key}");
                    controls.Value.PDesignation = GetValue($"txtPDesignation{controls.Key}"); 
                }
            }
    
            string GetValue(string id)
            {
                return ((TextBox)container.FindControl(id))?.Text;
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 20, 2020 6:08 PM
  • User-190697402 posted

    Hi asteranup,

    Thank you so much ,I have one request,can you please make a tutorial for this in your blog.It would be more helpful for beginners like me.

    I came to know about dictionary concepts from your coding only ,thank you so much for all the help.

    Tuesday, July 21, 2020 2:28 AM
  • User-190697402 posted

    Hi ateranup,

    i have changed the code as you mentioned,

    Change -

    Session["ControlGenerated"] = new Dictionary<int, PertnerData> { { 1, new PertnerData() } };

    to-

    Session["ControlGenerated"] = new Dictionary<int, PertnerData> {  } };

    but getting this error System.InvalidOperationException: 'Sequence contains no elements'  when i click on the add button.

    Thanks in Advance!

    Tuesday, July 21, 2020 2:31 AM
  • User348806598 posted

    Please debug and compare.

    Tuesday, July 21, 2020 9:46 AM