tags:

views:

801

answers:

4

Hi I am generating a DropDownList in my code behind file

    protected DropDownList CountryList() 
    {
        DropDownList ddl = new DropDownList();

        XDocument xmlDoc = XDocument.Load(Server.MapPath("Countries.xml"));
        var countries = from country in xmlDoc.Descendants("Country")
                        select new
                        {
                          Name = country.Element("name").Value,                              
                        };

        foreach (var c in countries)
        {
            ddl.Items.Add(c.Name);                
        }
        return ddl;
    }

I had dreams on then having <%= CountryList() %> on my aspx page. But when I do this it prints the string - "System.Web.UI.WebControls.DropDownList".

Can I make this way of doing it work or do I have to setup a ContentPlaceHolder and then add the DropDownList to the content?

Cheers

+2  A: 

The <%= %> is only a shorthand to the Response.Write method, you should add the controls programatically

Or just add an asp:DropDownList tag there you want it, and then in the code behind, you can bind the data directly from your Linq to XML query, using the DataSource property, and the DataBind() method.

For example:

On your .aspx file:

<asp:DropDownList ID="CountryListDropDown" runat="server">
</asp:DropDownList>

On your code-behind Page_Load:

CountryListDropDown.DataSource = countries; // your query
CountryListDropDown.DataBind();

Since your query has only one selected field, you don't have to specify the DataValueField and DataTextField values.

CMS
Cheers, that worked a charm
Tim
+1  A: 

The <%=...%> tags are preprocessed by the ASP.NET page to mean <% Response.Write(...) %> therefore your approach isn't going to work and you will need a ContentPlaceHolder, Panel, PlaceHolder or other naming container to add the DropDownList to.

Also if you want to have the page postbacks etc working as well you will need to create (and possibly populate) the DDL on the Page Init event and give it an ID otherwise you may end up with inconsistent view state.

David McEwing
+1  A: 

Declare the DropDownList like normal in your aspx page and then add the items in your Page_Load() or wherever else you are doing data binding.

AndyMcKenna
+1  A: 

DropDownList ddl = new DropDownList(); ddl.ID = "test"; form1.Controls.Add(ddl);//your formID

mike