简体   繁体   English

如何从C#中的动态创建的下拉列表创建动态文本框

[英]how to create a dynamic textbox from dynamically created drop down list in c#

i want to create the number of dynamic text boxes (values selected in drop down list ranging from 1 to 5) 我想创建多个动态文本框(在下拉列表中选择的值,范围从1到5)

note : drop down list list is also a dynamically created control 注意:下拉列表列表也是动态创建的控件

here sample code : 这里的示例代码:

    Table table=new Table();

    for (int i = 1; i <= 5; i++)
    {
        TableRow row = new TableRow();
        TableCell cell = new TableCell();

        DropDownList drp_splzn = new DropDownList();

        drp_splzn.ID = i.ToString();
        drp_splzn.Items.Add("-SELECT SPECIALIZATION-");
        drp_splzn.Items.Add(new ListItem("1", "1"));
        drp_splzn.Items.Add(new ListItem("2", "2"));
        drp_splzn.Items.Add(new ListItem("3", "3"));
        drp_splzn.Items.Add(new ListItem("4", "4"));
        drp_splzn.Items.Add(new ListItem("5", "5"));


        cell.Controls.Add(drp_splzn);

        row.Cells.Add(cell);
        table.Rows.Add(row);
    }

i want textboxes to be created followed by respected drop down list... i know thats possible using postback and drop down list changed event... but i couldnot figure it out 我希望先创建文本框,然后创建受人尊敬的下拉列表...我知道可以使用回发和下拉列表更改事件...但是我无法弄清楚

Here is a solution to the final issue. 这是解决最终问题的方法。

The following picture is an illustration (you may change the textboxes contents and the new values will be kept between postbacks): 下图是说明(您可以更改文本框的内容,并且新值将在回发之间保留):

许多选择

We are now facing the need to keep the already displayed textboxes displayed and also to keep the values they hold. 我们现在正面临着需要保持已经显示的文本框 displayed同时也保持其所持有的价值。 T he key to doing this is using the ViewState object. 实现此目的的关键是使用ViewState对象。 We will do that by enabling it on every control of which we want its state to be persisted. 我们将通过在希望其状态保持不变的每个控件上启用它来做到这一点。 On the other hand ASP .NET's engine will not recreate our controls for us, but when they are available it will use the ViewState mechanism against them. 另一方面,ASP .NET的引擎不会为我们重新创建控件,但是当它们可用时,它将对它们使用ViewState机制。

So first of all let's create a Dictionary object. 因此,首先让我们创建一个Dictionary对象。 We will use it to hold two informations. 我们将使用它来保存两个信息。 Number 1 a used dropdownlist and number 2 the selected value on that dropdownlist . 1号是一个已used下拉列表,2号是selected value on that dropdownlistselected value on that dropdownlist We create it as a static variable just like we did the boolean hasDropDowns 我们将其创建为静态变量,就像我们执行布尔hasDropDowns一样

public partial class WebForm1 : System.Web.UI.Page
{
    static bool hasDropDowns = false;
    static Dictionary<int, int> textBoxesStateDictionnary = new Dictionary<int, int>();

... ...

We will use the dropdownlist's id as a key and the selected value on that dropdownlist as the associated value. 我们将使用下拉列表的ID作为键,并使用该下拉列表中的选定值作为关联值。

Then we need to change our selectindex changed event handler. 然后,我们需要更改选择索引已更改的事件处理程序。 When a value is selected and we create the textboxes we need to add a new entry in the Dictionary. 选择一个值并创建文本框后,我们需要在字典中添加一个新条目。 Here is the new version of the selectindex changed event handler 这是selectindex更改事件处理程序的新版本

 void drp_splzn_SelectedIndexChanged(object sender, EventArgs e)
    {

        DropDownList chosenDropDown = (DropDownList)sender;

        Int32 pickedValue = Int32.Parse(chosenDropDown.SelectedValue);

        Table table = // new Table();
         (Table)Page.Form.FindControl("table" + chosenDropDown.ID);

        for (int i = 0; i < pickedValue; i++)
        {

            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Attributes.Add("runat", "server");

            TextBox txt_splzn = new TextBox();

            txt_splzn.ID = "txtB_" + chosenDropDown.ID + "_" + i.ToString();
            txt_splzn.Text = "Text Number " + i.ToString();
            txt_splzn.EnableViewState = true;

            cell.Controls.Add(txt_splzn);

            row.Cells.Add(cell);
            table.Rows.Add(row);

        }

        textBoxesStateDictionnary.Add(Int32.Parse(chosenDropDown.ID), Int32.Parse(chosenDropDown.SelectedValue));

    }

As you can see in the last line of code the key is the chosen drop down list's ID and the corresponding value, it's selected value. 正如您在代码的最后一行中看到的那样,键是所选下拉列表的ID和对应的值(即所选值)。

Also we had to change the textbox id since the previous ids were made of a litteral and the selected value. 另外,由于先前的ID是由乱扔垃圾和选定的值组成的,因此我们还必须更改文本框ID。 If we had kept it the same, the Page.Form.FindControl method would raise an exception: the IDs are to be unique. 如果我们保持不变,则Page.Form.FindControl方法将引发异常:ID将是唯一的。

Now we need to impact the Page_Load event handler. 现在我们需要影响Page_Load事件处理程序。 Right after we recreate a Drop down list we look into the Dictionary to see if there is a corresponding entry (using it's ID). 在我们重新创建一个下拉列表之后, 我们立即查看字典以查看是否存在相应的条目(使用其ID)。 If there is, we recreate as much Textboxes as indicated by the corresponding value in the dictionary's entry . 如果存在,我们将重新创建字典条目中相应值所指示的文本框 And then we trust the ViewState to do it's work since when we created the Textboxes we activated the ViewState (see txt_splzn.EnableViewState = true; ) 然后,我们信任ViewState来执行此操作,因为创建文本框时我们激活了ViewState(请参阅txt_splzn.EnableViewState = true;

Here is the Page_Load event handler's code 这是Page_Load事件处理程序的代码

 protected void Page_Load(object sender, EventArgs e)
    {

        if (Page.IsPostBack)
        {
            if (!hasDropDowns)
            {
                return;
            }

            Table table = new Table();

            for (int i = 1; i <= 5; i++)
            {
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                cell.Attributes.Add("runat", "server");

                DropDownList drp_splzn = new DropDownList();

                drp_splzn.ID = i.ToString();
                drp_splzn.Items.Add("-SELECT SPECIALIZATION-");
                drp_splzn.Items.Add(new ListItem("1", "1"));
                drp_splzn.Items.Add(new ListItem("2", "2"));
                drp_splzn.Items.Add(new ListItem("3", "3"));
                drp_splzn.Items.Add(new ListItem("4", "4"));
                drp_splzn.Items.Add(new ListItem("5", "5"));

                drp_splzn.SelectedIndexChanged += drp_splzn_SelectedIndexChanged;
                drp_splzn.AutoPostBack = true;
                drp_splzn.EnableViewState = true;


                cell.Controls.Add(drp_splzn);

                row.Cells.Add(cell);
                table.Rows.Add(row);

                TableRow rowT = new TableRow();
                TableCell cellT = new TableCell();
                cellT.Attributes.Add("runat", "server");

                Table table2 = new Table();

                table2.ID = "table" + i.ToString();


                int retrievedValue = -1;
                if (textBoxesStateDictionnary.TryGetValue(i, out retrievedValue))
                {
                    for (int j = 0; j < retrievedValue; j++)
                    {
                        // Recreate them
                        TableRow rowTT = new TableRow();
                        TableCell cellTT = new TableCell();
                        cellTT.Attributes.Add("runat", "server");

                        TextBox txt_splzn = new TextBox();

                        txt_splzn.ID = "txtB_" + i +"_" + j.ToString();

                        txt_splzn.EnableViewState = true;

                        cellTT.Controls.Add(txt_splzn);
                        rowTT.Controls.Add(cellTT);
                        table2.Controls.Add(rowTT);

                    }

               }

                cellT.Controls.Add(table2);

                rowT.Cells.Add(cellT);
                table.Rows.Add(rowT);
            }

            this.Controls.Add(table);

            Page.Form.Controls.Add(table);

        }
        else
        {

        }

    }

And that's it. 就是这样。

I understand you have dynamically added dropdown list and you want to create text boxes depending on the selected value on a dropdownlist 我了解您已动态添加了下拉列表,并且要根据下拉列表上的选定值创建文本框

First I added a button a dynamically create the DropDownlist objects after clicking on the button 首先,我添加了一个按钮,并在单击按钮后动态创建了DropDownlist对象

 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Make DropDowns" />

Then I create the DropDownlist inside the Button_Click handler event (this event handler can be created simply by double - clicking on this button which is static) 然后,我在Button_Click处理程序事件中创建DropDownlist(可以通过双击此静态按钮来创建此事件处理程序)

All I am doing in this handler is to use your dropdown list creation code and then add the table in the controls of the page's form object. 我在此处理程序中所做的全部工作就是使用您的下拉列表创建代码,然后将表格添加到页面的表单对象的控件中。 Otherwise you have an error message that tells you you need to put it in a runat = server like form. 否则,您将收到一条错误消息,提示您需要将其放入类似runat = server表格中。

I am also using a static boolean variable that allows me to keep the information that the DropDownlist have been created 我还使用了一个静态布尔变量,该变量允许我保留DropDownlist已创建的信息

Here is this event's handler code 这是此事件的处理程序代码

 protected void Button1_Click(object sender, EventArgs e)
    {

        Table table = new Table();

        for (int i = 1; i <= 5; i++)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Attributes.Add("runat", "server");

            DropDownList drp_splzn = new DropDownList();

            drp_splzn.ID = i.ToString();
            drp_splzn.Items.Add("-SELECT SPECIALIZATION-");
            drp_splzn.Items.Add(new ListItem("1", "1"));
            drp_splzn.Items.Add(new ListItem("2", "2"));
            drp_splzn.Items.Add(new ListItem("3", "3"));
            drp_splzn.Items.Add(new ListItem("4", "4"));
            drp_splzn.Items.Add(new ListItem("5", "5"));

            drp_splzn.SelectedIndexChanged += drp_splzn_SelectedIndexChanged;
            drp_splzn.AutoPostBack = true ;
            drp_splzn.EnableViewState = true;


            cell.Controls.Add(drp_splzn);

            row.Cells.Add(cell);
            table.Rows.Add(row);
        }

        this.Controls.Add(table);

        Page.Form.Controls.Add(table);
        hasDropDowns = true;
    }

So my boolean variable is called hasDropDowns and is set to true once the dropdown controls are added. 因此,我的布尔变量称为hasDropDowns ,一旦添加了下拉控件,它就会设置为true。 This will be usefull to handle the fact that the Http protocole is stateless and therefore we will need to handler ourselves the state of our controls. 这将有助于处理Http协议是无状态的事实,因此我们将需要处理自己的控件状态。 Otherwise after the page is Postback their state is cleared and ASP .NET engine won't be able to find the control that trigger the Post back event nore it state and we will have every dynamic control's state lost. 否则,在页面为回发后,它们的状态将被清除,而ASP .NET引擎将无法找到触发回发事件的控件,而该状态将不会被释放,我们将丢失所有动态控件的状态。

As you can see when I created the dropdownlist I also attached a click event handler on them and made them autopostback = true. 如您所见,当我创建下拉列表时,我还在它们上附加了click事件处理程序,并使它们autopostback = true。 That way they will trigger the post back as soon as their value change. 这样,他们将在其价值更改后立即触发该帖子。 This is to demonstrate how to solve the issue, you may customize it as you want to. 这是为了演示如何解决此问题,您可以根据需要自定义它。

Now the dropdownlist selectindexchanged event handler 现在,下拉列表selectindexchanged事件处理程序

void drp_splzn_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList chosenDropDown = (DropDownList)sender;
        Int32 pickedValue = Int32.Parse(chosenDropDown.SelectedValue);
        Table table = new Table();

        for (int i = 0; i < pickedValue; i++)
        {

            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Attributes.Add("runat", "server");

            TextBox txt_splzn = new TextBox();

            txt_splzn.ID = "txtB" +  i.ToString();
            txt_splzn.Text = "Text Number " + i.ToString();

            cell.Controls.Add(txt_splzn);

            row.Cells.Add(cell);
            table.Rows.Add(row);

        }

        Page.Form.Controls.Add(table);

        Response.Write("Change occured...");


    }

As you can see in the code it created as many textboxes as the selected value in the dropdown list and I put a simple text in the Text properties of these textboxes. 正如您在代码中看到的那样,它在下拉列表中创建了与所选值一样多的文本框,并且在这些文本框的Text属性中放置了一个简单的文本。 I also gave them unique IDs. 我还给了他们唯一的ID。

Again we add the table to the Page's form control. 再次,我们将表格添加到Page的表单控件中。

Now we need to handle the PostBack phenomenon correctly. 现在,我们需要正确处理PostBack现象。 In Asp.Net and because HTTP is stateless the engine allows us to process two kinds of Page Load. 在Asp.Net中,由于HTTP是无状态的,因此引擎允许我们处理两种页面加载。 The page load that occurs the first time: in that case Page.IsPostback is false (first load) and the Page Load that occurs all the other times (in that case Page.IsPostBack is true) 第一次发生的页面加载:在这种情况下,Page.IsPostback为false(第一次加载),而在所有其他时间发生的页面加载(在这种情况下,Page.IsPostBack为true)。

So here when the Page is PostBack and hasDropDowns is true then it means that I have already gone through the process of creating the dynamic dropdowns and assigning them selectindex change handlers, therefore to have a consistent state I need to recreated them exactly as I did the first time. 所以在这里,当Page是PostBack并且hasDropDowns为true时,这意味着我已经完成了创建动态下拉列表并为其分配selectindex更改处理程序的过程,因此要获得一致的状态,我需要像创建新的那样完全重新创建它们。第一次。 Then and only then will ASP.NET be able to correctly bind them to the selectindexchange event handler and process the event correctly. 然后只有这样,ASP.NET才能将它们正确绑定到selectindexchange事件处理程序,并正确处理该事件。

Here is the Page.Load event handler's code along with the declaration of the hasDropDowns static boolean variable 这是Page.Load事件处理程序的代码,以及hasDropDowns静态布尔变量的声明。

 static bool hasDropDowns = false;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Page.IsPostBack)
        {
            if (!hasDropDowns)
            {
                return;
            }

            Table table = new Table();

            for (int i = 1; i <= 5; i++)
            {
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                cell.Attributes.Add("runat", "server");

                DropDownList drp_splzn = new DropDownList();

                drp_splzn.ID = i.ToString();
                drp_splzn.Items.Add("-SELECT SPECIALIZATION-");
                drp_splzn.Items.Add(new ListItem("1", "1"));
                drp_splzn.Items.Add(new ListItem("2", "2"));
                drp_splzn.Items.Add(new ListItem("3", "3"));
                drp_splzn.Items.Add(new ListItem("4", "4"));
                drp_splzn.Items.Add(new ListItem("5", "5"));

                drp_splzn.SelectedIndexChanged += drp_splzn_SelectedIndexChanged;
                drp_splzn.AutoPostBack = true;
                drp_splzn.EnableViewState = true;


                cell.Controls.Add(drp_splzn);

                row.Cells.Add(cell);
                table.Rows.Add(row);
            }

            this.Controls.Add(table);

            Page.Form.Controls.Add(table);

        }
        else
        {

        }



    }

Here are some images that shows that it is working fine. 这是一些图片,表明它工作正常。

下拉列表

选择一个值

结果

Here is the solution to your last issue. 这是您上一期的解决方案。 It is exactly the implementation of the idea that I shared with you as comment. 这正是我与您分享的想法的实现。

Here are some illustration images and the code below 这是一些插图图像和下面的代码

Illustration_1

Illustration_2

First in the protected void Button1_Click method, I add an empty table under each dropdownlist. 首先,在protected void Button1_Click方法中,在每个下拉列表下方添加一个空表。 Since it is empty it won't show up at first. 由于为空,因此一开始不会显示。

Here is the code for that: 这是该代码:

protected void Button1_Click(object sender, EventArgs e)
    {

        Table table = new Table();

        for (int i = 1; i <= 5; i++)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Attributes.Add("runat", "server");

            DropDownList drp_splzn = new DropDownList();

            drp_splzn.ID = i.ToString();
            drp_splzn.Items.Add("-SELECT SPECIALIZATION-");
            drp_splzn.Items.Add(new ListItem("1", "1"));
            drp_splzn.Items.Add(new ListItem("2", "2"));
            drp_splzn.Items.Add(new ListItem("3", "3"));
            drp_splzn.Items.Add(new ListItem("4", "4"));
            drp_splzn.Items.Add(new ListItem("5", "5"));

            drp_splzn.SelectedIndexChanged += drp_splzn_SelectedIndexChanged;
            drp_splzn.AutoPostBack = true;
            drp_splzn.EnableViewState = true;


            cell.Controls.Add(drp_splzn);

            row.Cells.Add(cell);
            table.Rows.Add(row);

            TableRow rowT = new TableRow();
            TableCell cellT = new TableCell();
            cellT.Attributes.Add("runat", "server");

            Table table2 = new Table();

            table2.ID = "table" + i.ToString();

            cellT.Controls.Add(table2);

            rowT.Cells.Add(cellT);
            table.Rows.Add(rowT);



        }

         this.Controls.Add(table);

        Page.Form.Controls.Add(table);
        hasDropDowns = true;
    }

Of course you have to duplicate these change in the Page_Load as I did here: 当然,您必须像在这里一样在Page_Load复制这些更改:

 protected void Page_Load(object sender, EventArgs e)
    {

        if (Page.IsPostBack)
        {
            if (!hasDropDowns)
            {
                return;
            }

            Table table = new Table();

            for (int i = 1; i <= 5; i++)
            {
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                cell.Attributes.Add("runat", "server");

                DropDownList drp_splzn = new DropDownList();

                drp_splzn.ID = i.ToString();
                drp_splzn.Items.Add("-SELECT SPECIALIZATION-");
                drp_splzn.Items.Add(new ListItem("1", "1"));
                drp_splzn.Items.Add(new ListItem("2", "2"));
                drp_splzn.Items.Add(new ListItem("3", "3"));
                drp_splzn.Items.Add(new ListItem("4", "4"));
                drp_splzn.Items.Add(new ListItem("5", "5"));

                drp_splzn.SelectedIndexChanged += drp_splzn_SelectedIndexChanged;
                drp_splzn.AutoPostBack = true;
                drp_splzn.EnableViewState = true;


                cell.Controls.Add(drp_splzn);

                row.Cells.Add(cell);
                table.Rows.Add(row);

                TableRow rowT = new TableRow();
                TableCell cellT = new TableCell();
                cellT.Attributes.Add("runat", "server");

                Table table2 = new Table();

                table2.ID = "table" + i.ToString();

                cellT.Controls.Add(table2);

                rowT.Cells.Add(cellT);
                table.Rows.Add(rowT);
            }

            this.Controls.Add(table);

            Page.Form.Controls.Add(table);

        }
        else
        {

        }



    }

And finally in the void drp_splzn_SelectedIndexChanged instead of instanciating a new Table with Table table = new Table(); 最后在void drp_splzn_SelectedIndexChanged而不是使用Table table = new Table();实例化一个新表Table table = new Table(); we replace this line of code with a code that retrieves the previous table control. 我们将这行代码替换为检索上一个表控件的代码。 the chosenDropDown that we retrieved in the first line of this method will help us: it's ID is the corresponding number. 在此方法的第一行中检索到的chosenDropDown将帮助我们:它的ID是相应的数字。 Therefore the ID to lookup is "table" + chosenDropDown.ID Also at the end of this method we don't have to add this table since it is already part of the page. 因此,要查找的ID是“表” + selectedDropDown.ID。在此方法的最后,我们也不必添加此表,因为它已经是页面的一部分了。 So I have commented the Page.Form.Controls.Add(table); 所以我评论了Page.Form.Controls.Add(table); line of code 代码行

Here is the corresponding code: 这是相应的代码:

void drp_splzn_SelectedIndexChanged(object sender, EventArgs e)
{

        DropDownList chosenDropDown = (DropDownList)sender;

        Int32 pickedValue = Int32.Parse(chosenDropDown.SelectedValue);

        Table table = // new Table();
         (Table)Page.Form.FindControl("table" + chosenDropDown.ID);

        for (int i = 0; i < pickedValue; i++)
        {

            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Attributes.Add("runat", "server");

            TextBox txt_splzn = new TextBox();

            txt_splzn.ID = "txtB" + i.ToString();
            txt_splzn.Text = "Text Number " + i.ToString();

            cell.Controls.Add(txt_splzn);

            row.Cells.Add(cell);
            table.Rows.Add(row);

        }

        //Page.Form.Controls.Add(table);

        Response.Write("Change occured...");


    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在c#中为动态下拉列表创建事件处理程序 - how to create event handler for dynamic drop down list in c# 如何使用窗体形式在C#中创建动态下拉列表 - how to create a dynamic drop down list in C# with window forms 从下拉列表生成动态文本框(C#) - Dynamic text box generation from drop down list(C#) 如何从动态添加的标签中检索数据,asp.net c#中动态添加的div标签中的下拉列表 - how to retrieve data from dynamically added label,drop down list in dynamically added div tag in asp.net c# 如何从下拉列表中选择值(Selenium C#) - How to select value from the drop down list (Selenium C#) 如何知道特定文本框中是否有更改,该文本框是在C#中动态创建的 - How to know if there is a changes in a specific textbox, the textbox is dynamically created in C# 在C#中创建动态创建的类的列表 - create list of dynamically created classes in c# 从 Excel 的下拉列表中检索选定的值(在 C# 中创建) - Retrieve selected value from Drop Down List in Excel (created in C#) 在ASP.NET C#中动态填充数据库中的下拉列表 - fill drop down list from database dynamically in asp.net c# 如何将下拉列表绑定到ASP.Net MVC C#中的动态生成的变量 - How to bind a drop down list to a dynamically generated variable in ASP.Net MVC C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM