2009-06-15 40 views
0

嗨,我在我的代碼生成隱藏文件從代碼生成的DropDownList後面

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; 
    } 

一個DropDownList我有那麼有我的aspx頁面上<%= CountryList()%>的夢想。但是當我這樣做時,它會打印字符串 - 「System.Web.UI.WebControls.DropDownList」。

我可以使這種方式做到這一點嗎?或者我必須設置ContentPlaceHolder,然後將DropDownList添加到內容中嗎?

乾杯

+0

歡呼的評論 謝謝 – Marklar 2009-06-15 05:31:44

回答

3

<%= %>只是一個速記Response.Write方法,你應該add the controls programatically

或者只是添加一個asp:DropDownList的標籤有你想要的,然後後面的代碼,你可以直接使用DataSource屬性和DataBind()方法將數據從Linq綁定到XML查詢。

例如:

在您的.aspx文件:

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

在你的後臺代碼的Page_Load:

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

由於您的查詢只有一個選擇的領域,你不」不得不指定DataValueField和DataTextField值。

+0

乾杯,這工作的魅力 – Marklar 2009-06-16 23:21:42

1

<%=...%>標籤由ASP.NET頁面預處理,意味着<% Response.Write(...) %> 因此你的做法是行不通的,你會需要的ContentPlaceHolder,面板,佔位符或其他命名容器中添加的DropDownList來。

此外,如果你想讓頁面回傳等工作,你將需要在頁面初始化事件上創建(也可能是填充)DDL並給它一個ID,否則你可能會以不一致的視圖狀態結束。

1

在你的aspx頁面聲明DropDownList與普通的一樣,然後將這些項目添加到Page_Load()或你正在做數據綁定的任何地方。

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