且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取动态下拉列表值。

更新时间:2022-10-26 10:20:44

如上所述,动态添加的控件应该是在每个回发上重新创建以将其保留在页面上。请参阅: ASP.Net持续动态控制:动态控件在ASP.Net中的PostBack后消失



这里有一个关于如何动态生成 TextBox行的快速示例控制到



  private   int  numOfRows =  0 ; 
private int numOfColumns = 0 ;

private void GenerateTable( int colsCount, int rowsCount){

// 创建表并将其添加到页面
表table = new Table();
table.ID = Table1;
Page.Form.Controls.Add(table);

// 现在遍历表并添加控件
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();

// 为每个添加的TextBox设置唯一ID
tb.ID = TextBoxRow _ + i + Col _ + j;
// 将控件添加到TableCell
cell.Controls.Add( TB);
// 将TableCell添加到TableRow
row.Cells.Add(细胞);
}

// 将TableRow添加到表中
table.Rows.Add(row);
}
}





上面的代码只是创建一个空白表并将其添加到表单中。然后根据 rowsCount 的值,用 TextBoxes 的列和行填充表格。 colsCount



现在,您可以在 Page_Load 事件上调用上面的方法来重新创建回发时。



受保护 void Page_Load( object sender,EventArgs e){
// 两个参数全局声明
GenerateTable(numOfColumns,numOfRows);
}





然后你可以在Button Click事件中调用方法GenerateTable(),如下所示:



 受保护  void  Button1_Click(  object  sender,EventArgs e){
// 检查输入是否为数字
if int .TryParse(TextBox1 .Text.Trim(), out numOfColumns)&& int .TryParse(TextBox2.Text。修剪(), out numOfRows))
{
// 根据输入生成表
GenerateTable(numOfColumns,numOfRows);

// 将当前行和列存储在ViewState中作为回发时的参考值
ViewState [ cols] = numOfColumns;
ViewState [ rows] = numOfRows;
}
else
{
Response.Write( 值不是数字!);
}
}





就本例而言,我们使用了两个 TextBoxes ,以便您能够测试 numOfColumns numOfRows 参数的值。在您的情况下,您可以绕过它并使用所选DropDownList的值。例如:



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





最后,既然我们已经动态地用 TextBoxes 创建了我们的,我们可以获取输入的值来自动态 TextBox 使用 Request.Form 集合。这是下面的代码块。



  protected   void  Button2_Click( object  sender,EventArgs e){
// 检查如果ViewState值为null
if (ViewState [ cols]!= null && ViewState [ rows]!= null
{
// 在页面中查找表
表table =(表)Page.FindControl( Table1);
if (table!= null
{
// 重新创建包含当前行和列的表
GenerateTable( int .Parse(ViewState [ cols]。ToString() ), int .Parse(ViewState [ rows]的ToString()))。

// 现在我们可以遍历Table的行和列并获取值来自TextBoxes
for int i = 0 ; i < int .Parse(ViewState [ rows]。ToString()); i ++)
{
for int j = 0 ; j < int .Parse(ViewState [ cols]。ToString()); j ++)
{
// 打印输入的值
if (Request.Form [ TextBoxRow _ + i + Col _ + j]!= string .Empty)
{
Response.Write(Request.Form [ TextBoxRow _ + i + Col _ + j] + < BR />);
}
}
}
}
}
}





就是这样。希望有所帮助。



如果您还在寻找 GridView 解决方案,您可以查看我的文章: 在GridView中动态添加和删除行并一次保存所有行 [ ^ ]


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;


    }
}

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.

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.

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:

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:

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.

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[^]