smatter
smatter

Reputation: 29248

Retrieve data from dynamically created controls

I am dynamically creating several dropdown list on the selection changed event of a main (static) dropdown list. These are created in The TableCell of default Table. When submit button is clicked I need to load a new page with selected values of dropdown as parameters. Basically I need to get the dropdown results in the second page.

This is how dropboxes are created:

    while (reader.Read())
    { 
        pcID = int.Parse(reader["fk_pcID"].ToString());
        pcDesc = GetpcDescription(pcID);
        List<Product> prodList = GetProductsBypcID(pcID);
        DropDownList ddList = new DropDownList();
        ddList.ID = "ddlPC" + pcID;
        foreach(Product prod in prodList)
        {
            ddList.Items.Add(new ListItem(prod.ProductName, prod.ProductID.ToString()));
        }
        TableCell cell1 = new TableCell();
        cell1.Text = pcDesc;

        TableCell cell2 = new TableCell();
        cell2.Controls.Add(ddList);

        TableRow row = new TableRow();
        row.Cells.Add(cell1);
        row.Cells.Add(cell2);

        table.Rows.Add(row);  
    }

EDIT: The above code runs at the selection changed event of a dropdown which is set to runat server. But dynamically created dropdowns are not set to run at server

Upvotes: 1

Views: 721

Answers (2)

James Johnson
James Johnson

Reputation: 46067

This sounds like a good candidate for the DynamicControlsPlaceholder. It will preserve your dynamic controls automatically, without requiring any additional code on the page. If you need to create the controls OnSelectedIndexChanged, I think this might be the simplest solution.

It's a free component, and you can download it here.

http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx

Upvotes: 0

Michael Jasper
Michael Jasper

Reputation: 8068

Are these drop-down boxes runat="server"? Meaning: did you created them programmaticly via a .net post-back event through the code behind? If so, just get the selected value the same as you would with any other control, and then pass it through a query string or a cookie.

Are these standard html drop-down lists? Good luck reading them from a code-behind. That gets you all tangled up in the viewstate, and while technically possible, is realistically not feasible.

If the second option is the case, it might be a much better option to have your button target a JavaScript function that gets the selected values and then passes them via querystring. Then on the other page you can read the querystrings from the code-behind, or on the client-side.

Upvotes: 1

Related Questions