Click here to Skip to main content
15,915,319 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written code for dynamically creating a table. The table contains a textbox and a Dropdownlist. I trying to create the table based on selected dropdownlist value when I select dropdown list like "Splitter1:5" than Table row will creating 5 . First time it has done successfully, when I try to second time I did not get the value of dropdown list. i am sharing my code please help me.

What I have tried:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="ddlTextBoxes" runat="server">
                <asp:ListItem Value="2" Text="Splitter1:2" />
                <asp:ListItem Value="4" Text="Splitter1:4" />
                <asp:ListItem Value="8" Text="Splitter1:8" />
                <asp:ListItem Value="1" Text="Joint" />
                <asp:ListItem Value="0" Text="OLT" />
            </asp:DropDownList>
            <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" /><br />
            <asp:Panel ID="container" runat="server" Visible="false"> <asp:Button ID="btnSubmit" runat="server" Text="Process" OnClick="Submit" /></asp:Panel>
           
               
           
        </div>
    </form>
</body>
</html>







using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class testform : System.Web.UI.Page
{
    DropDownList DDL; int i;
    ArrayList arry_value = new ArrayList(); object[] obj;
    Panel pn;

    protected void Page_Load(object sender, EventArgs e)
    {
        //ViewState["droplist"] = obj;
    }



    protected void btnAdd_Click(object sender, EventArgs e)
    {
        int numOfTxt = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value);
        //  DataTable dt = new DataTable();
        //dt.Columns.Add("First Textbox");
        //  dt.Columns.Add("Dropdownlist");
        //  dt.Columns.Add("Last Textbox");
        var table = new Table();

        for (i = 0; i < numOfTxt; i++)
        {
            var row = new TableRow();
            var cell = new TableCell();

            // var thr = new TableHeaderRow();
            // var heading = new TableHeaderCell();
            //TableHeaderCell thPNumber = new TableHeaderCell();

            // cell.Attributes.Add("runat", "server");

            TextBox textbox = new TextBox();
            textbox.ID = "Textbox" + i;
            textbox.Text = "text" + i;

            textbox.Width = new Unit(180);

            TextBox textbox1 = new TextBox();
            textbox1.ID = "Textbox1" + i;
            textbox1.Text = "text1" + i;
            textbox1.Width = new Unit(180);

            DDL = new DropDownList();
            DDL.ID = "DDL1" + i;

            DDL.Items.Add("Select Splitter");
            DDL.Items.Add(new ListItem("Splitter1:2", "2"));
            DDL.Items.Add(new ListItem("Splitter1:4", "4"));
            DDL.Items.Add(new ListItem("Splitter1:8", "8"));
            DDL.Items.Add(new ListItem("Joint", "1"));
            DDL.Items.Add(new ListItem("ONT", "0"));
            DDL.AutoPostBack = true;
            DDL.SelectedIndexChanged += new System.EventHandler(DDL_SelectedIndexChanged);
         
            cell.Controls.Add(textbox1);
            cell.Controls.Add(DDL);
            cell.Controls.Add(textbox);
          
            row.Cells.Add(cell);
         

            table.Rows.Add(row);
            arry_value.Add(DDL.ID);
            foreach (object obj in arry_value)
            {
                var idcollection = new string[] { obj.ToString() };
            }
          
        }
        pn = new Panel();
        pn.ID = "pan" + i + 1;
        this.form1.Controls.Add(pn);
        container.Visible = true;

        Button btnSubmit = new Button();
        btnSubmit.ID = "btnSubmit";
        btnSubmit.Text = "Processone";
        btnSubmit.Click += new System.EventHandler(Submit);
        container.Controls.Add(table);
        //pn.Controls.Add(btnSubmit);
      //  container.Controls.AddAt(0, table);

    }

    protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
    }
    protected void Submit(object sender, EventArgs e)
    {
        //Student stud = (Student)ViewState["CurrentStudent"];
        //DropDownList ddl = (DropDownList)container.FindControl("DDL1"+i);
         int numOfTxt = 5;
        Label lb = new Label();
        //lb.Text = DDL.SelectedValue.ToString();
        //int numOfTxt = Convert.ToInt32(lb);
        string drpvalue;
        for (int j = 0; j < Convert.ToInt32(ddlTextBoxes.SelectedItem.Value); j++)
        {
            drpvalue = "DDL12" + i + ".SelectedItem.Value";
            //int te = Convert.ToInt32(drpvalue);
          //  numOfTxt += Convert.ToInt32(DDL120.SelectedItem.Value);
        }
        //int numOfTxt = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value);
        var table = new Table();
        DataTable dt = new DataTable();
        for (int i = 0; i < numOfTxt; i++)
        {
            var row = new TableRow();
            var cell = new TableCell();
            // dt.Columns.Add("TextOne1");
            cell.Attributes.Add("runat", "server");

            TextBox textbox = new TextBox();
            textbox.ID = "Textbox" + i;
            textbox.Text = "text" + i;
            textbox.Width = new Unit(180);

            TextBox textbox1 = new TextBox();
            textbox1.ID = "Textbox1" + i;
            textbox1.Text = textbox1.Text;
            textbox1.Width = new Unit(180);

            DropDownList DDLs = new DropDownList();
            DDLs.ID = "DDL12" + i;
            //  count= Convert.ToInt32( DDL.ID = "DDL12" + i);
            DDLs.Items.Add("Select Splitter");
            DDLs.Items.Add(new ListItem("Splitter1:2", "2"));
            DDLs.Items.Add(new ListItem("Splitter1:4", "4"));
            DDLs.Items.Add(new ListItem("Splitter1:8", "8"));
            DDLs.Items.Add(new ListItem("Joint", "1"));
            DDLs.Items.Add(new ListItem("ONT", "0"));

            //DDLs.AutoPostBack = true;
           // DDLs.TextChanged += dropDown_TextChanged;

            //            dt.Rows.Add(textbox1);
            cell.Controls.Add(textbox1);
            // dt.Columns.Add("ListDropdown");
            cell.Controls.Add(DDLs);
            // dt.Columns.Add("Textbodx");
            cell.Controls.Add(textbox);
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }
        Button btnSubmit = new Button();
        btnSubmit.ID = "btnSubmit";
        btnSubmit.Text = "Process";
        btnSubmit.Click += new System.EventHandler(Submit);

        Panel pans = new Panel();
        pans.ID = "panss";
        this.form1.Controls.Add(pans);
        pans.Controls.AddAt(0, table);
        pans.Controls.Add(btnSubmit);

        pans.Visible = true;
        //pn.Visible = true;


    }
}
Posted
Updated 17-Jul-18 14:09pm
v2
Comments
F-ES Sitecore 17-Jul-18 8:40am    
Any controls you create yourself are not "remembered" between postbacks, so you have to recreate them each time on load.
Ziee-M 17-Jul-18 9:34am    
You should have set this comment as an answer.

1 solution

As mentioned, dynamically added controls should be recreated on each postbacks to retain them on the page. See: ASP.Net Persist Dynamic Controls: Dynamic Controls disappear after PostBack in ASP.Net

Here's a quick example on how to dynamically generate rows of TextBox controls to a table.

C#
private int numOfRows = 0;
private int numOfColumns = 0;

private void GenerateTable(int colsCount, int rowsCount){

        //Creat the Table and Add it to the Page
        Table table = new Table();
        table.ID = "Table1";
        Page.Form.Controls.Add(table);

        // Now iterate through the table and add your controls 
        for (int i = 0; i < rowsCount; i++){
            TableRow row = new TableRow();
            for (int j = 0; j < colsCount; j++){
                TableCell cell = new TableCell();
                TextBox tb = new TextBox();

                // Set a unique ID for each TextBox added
                tb.ID = "TextBoxRow_" + i + "Col_" + j;
                // Add the control to the TableCell
                cell.Controls.Add(tb);
                // Add the TableCell to the TableRow
                row.Cells.Add(cell);
            }

            // Add the TableRow to the Table
            table.Rows.Add(row);
        }
}


The code above simply creates a blank table and add it to the form. It then fill the table with columns and rows of TextBoxes based from the values of rowsCount and colsCount.

Now, you can call the method above on Page_Load event to recreate the table when it postbacks.

C#
protected void Page_Load(object sender, EventArgs e){
         // the two paramters are declared globally
         GenerateTable(numOfColumns, numOfRows);
}


You can then call the method GenerateTable() at Button Click event like this:

C#
protected void Button1_Click(object sender, EventArgs e){
        //Check if the inputs are numbers
        if (int.TryParse(TextBox1.Text.Trim(), out numOfColumns) && int.TryParse(TextBox2.Text.Trim(), out numOfRows))
        {
            //Generate the Table based from the inputs
            GenerateTable(numOfColumns, numOfRows);

            //Store the current Rows and Columns In ViewState as a reference value when it post backs
            ViewState["cols"] = numOfColumns;
            ViewState["rows"] = numOfRows;
        }
        else
        {
            Response.Write("Values are not numeric!");
        }
}


Just for this example, we've use two TextBoxes for you to be able to test the values of numOfColumns and numOfRows parameters. In your case, you could bypass it and use the value of the DropDownList selected. For example:

C#
numOfColumns = 1;
numOfRows = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value;
GenerateTable(numOfColumns, numOfRows);


Finally, since we're done creating our Table with TextBoxes dynamically, we can grab the values entered from the dynamic TextBox using Request.Form collection. Here’s the code block below.

C#
protected void Button2_Click(object sender, EventArgs e){
    //Check if ViewState values are null
    if (ViewState["cols"] != null && ViewState["rows"] != null)
    {
        //Find the Table in the page
        Table table = (Table)Page.FindControl("Table1"); 
        if (table != null)
        {
            //Re create the Table with the current rows and columns
            GenerateTable(int.Parse(ViewState["cols"].ToString()), int.Parse(ViewState["rows"].ToString()));

            // Now we can loop through the rows and columns of the Table and get the values from the TextBoxes
            for (int i = 0; i < int.Parse(ViewState["rows"].ToString()) ; i++)
            {
                for (int j = 0; j < int.Parse(ViewState["cols"].ToString()); j++)
                {
                    //Print the values entered
                    if (Request.Form["TextBoxRow_" + i + "Col_" + j] != string.Empty)
                    {
                        Response.Write(Request.Form["TextBoxRow_" + i + "Col_" + j] + "<BR/>");
                    }
                }
            }
        }
    }
}


That's it. Hope that helps.

If you are also looking for a GridView solution, you can check my article about: Dynamically Adding and Deleting Rows in GridView and Saving All Rows at Once[^]
 
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