如何以编程方式创建和填充下拉列表

时间:2013-10-03 20:55:23

标签: asp.net placeholder

我试图使用这样的for循环创建下拉列表:

    private void Page_Load(object sender, System.EventArgs e)
    {
        //build placeholder
        for(int x = 0; x <= 10; x++) {

            DropDownList dp = new DropDownList();
            dp.ID = "carrirerDp " + x.ToString();
            dp.DataSource = PhoneCarrierSqlDataSource;               
            dp.DataTextField = "carrier_name";
            dp.DataValueField = "crr_id";
            DropDownPlaceHolder.Controls.Add(dp);
            DropDownPlaceHolder.Controls.Add(new LiteralControl("<br>"));
        }     
    } 

已创建下拉列表但它们为空。 执行我用asp标记创建的那个

 <asp:DropDownList ID="PhoneCarrierDropDownList" runat="server" 
    DataSourceID="PhoneCarrierSqlDataSource" DataTextField="carrier_name" 
    DataValueField="crr_id">
 </asp:DropDownList>  

 <asp:SqlDataSource ID="PhoneCarrierSqlDataSource" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ApplicationServices %>" 
    SelectCommand="SELECT * 
                   FROM Table">
 </asp:SqlDataSource>

这是占位符:

 <asp:PlaceHolder id="Area1" runat="server"></asp:PlaceHolder>

1 个答案:

答案 0 :(得分:3)

你还没有数据包:

 dp.DataBind();