Add array of controls to an aspx page

后端 未结 5 2007
暗喜
暗喜 2021-01-06 08:13

I\'m trying to add an array of controls to an aspx page (C# code behind). These are the similar controls (search criteria for separate fields but will have the same values)

相关标签:
5条回答
  • 2021-01-06 08:21

    You should look into dynamically creating controls.

    http://support.microsoft.com/kb/317794

    0 讨论(0)
  • 2021-01-06 08:27

    Like @Mark Cidade says your best approach would be to create the controls in the code behind. They are just classes after all.

    The simplest approach would be to put a control such as a placeHolder control on in the markup and then create a collection of dropdown lists in a loop, assinging each one a unique id like @Mark Cidade says.

    From there it's a matter of adding them as child controls to the placeHolder or if you want them directly on the page you can add them to the page controls collection.

    0 讨论(0)
  • 2021-01-06 08:28

    You can give them valid IDs and put them all in an array yourself:

    <asp:DropDownList ID="FruitDropDown0" runat="server"/>
    <asp:DropDownList ID="FruitDropDown1" runat="server"/>
    

    protected void Page_Load(object sender, EventArgs e) {
       ListItem[] items = new ListItem[3];
       ...
    
       DropDownList[] lists = new DropDownList[] { FruitDropDown0
                                                  ,FruitDropDown1
                                                  ,...};
    
       foreach(DropDownList list in lists) {
          list.Items.AddRange(items);
          list.DataBind();
       }
    }
    
    0 讨论(0)
  • 2021-01-06 08:34

    Control.FindControl is what you're looking for. You can use it on any Control(like Page itself) to find controls via their NamingContainer. Put them e.g. in a Panel and use FindControl on it.

    for (int x = 0; x < 20; x++) {
        DropDownList ddlFruit = (DropDownList)FruitPanel.FindControl("FruitDropDown" + x);
        ddlFruit.Items.AddRange(items[x]);    
    }
    

    You can also create them dynamically:

    for (int x = 0; x < 20; x++) {
       DropDownList ddlFruit = new DropDownList();
       ddlFruit.ID = "FruitDropDown" + x
       ddlFruit.Items.AddRange(items[x]);  
       FruitPanel.Controls.Add(ddlFruit); 
    }
    

    You must recreate dynamically created controls on every postback at the latest in Page_Load with the same ID as before to ensure that ViewState is loaded correctly and events are triggered.

    0 讨论(0)
  • 2021-01-06 08:40

    From your question it looks like you are trying dynamically render controls on the screen

    Here is a good article on doing this.

    0 讨论(0)
提交回复
热议问题