2009-06-15 121 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