如何在C#中以编程方式添加DropDownList

时间:2015-06-26 07:17:33

标签: c# asp.net

所以我有一个应该显示DropDownList的母版页。然后我有一个应该创建DropDownList的类。但是因为我只有一个带有DDL的页面,所以我不想在masterpage.aspx中写入。所以我的问题是,如果甚至可以在C#中编写所有代码来创建DropDownList。我需要这样的东西吗?

<asp:Panel ID="pnlChannel" runat="server">

或者我可以这样做:

Panel pnlChannel = new Panel();

但如果我在代码隐藏中这样做它将不会显示任何内容

到目前为止,这是我的代码:

 public Panel GetDropDownList()
{
    // Create drop down list and data source
    Panel pnlChannel = new Panel();
    DropDownList ddlChannel = new DropDownList();
    ListItem limDefault = new ListItem();
    SqlDataSource sdsChannel = new SqlDataSource();

    // Configure data source
    sdsChannel.ConnectionString = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;
    sdsChannel.SelectCommand = "SELECT * FROM Kanal";
    sdsChannel.ID = "sdsChannel";

    // Configure drop down list
    ddlChannel.DataTextField = "Kanal";
    ddlChannel.DataValueField = "Kanal";
    ddlChannel.AppendDataBoundItems = true;
    ddlChannel.DataSourceID = "sdsChannel";



    // Configure default list item
    limDefault.Selected = true;
    limDefault.Text = "Alle";
    limDefault.Value = "-1";

    // Add controls to static panel in footer
    ddlChannel.Items.Add(limDefault);
    pnlChannel.Controls.Add(ddlChannel);
    pnlChannel.Controls.Add(sdsChannel);

    return pnlChannel;
}

我真的不知道自己要做什么,要在页面上显示它。 如果我调试它并执行页面,它会调用该方法,但它仍然不会显示在页面上

2 个答案:

答案 0 :(得分:2)

Html标记:

在.aspx页面上添加面板控件

<asp:Panel ID="Panel1" runat="server">
</asp:Panel>

代码隐藏:在页面加载

DropDownList ddl = new DropDownList();
ddl.DataSource = sdsChannel;
ddl.DataTextField = "Kanal";
ddl.DataValueField = "Kanal";
ddl.DataBind();
Panel1.Controls.Add(ddl);

Html标记:

在表单标记

下的母版页上添加了面板控件
<asp:Panel id="pnlMasterPage" runat="server">
</asp:Panel>

方法1:在母版页上on_load

DropDownList ddl = new DropDownList();
ddl.DataSource = sdsChannel;
ddl.DataTextField = "Kanal";
ddl.DataValueField = "Kanal";
ddl.DataBind();
pnlMasterPage.Controls.Add(ddl);

方法2:  如果要从子页面进行绑定,则在子页面on_load

上进行绑定
DropDownList ddl = new DropDownList();
ddl.DataSource = sdsChannel;
ddl.DataTextField = "Kanal";
ddl.DataValueField = "Kanal";
ddl.DataBind();
Panel pnl = this.Master.FindControl("pnlMasterPage") as Panel;
pnl.Controls.Add(ddl);

答案 1 :(得分:0)

我的经验基于使用C#的WinForms,但它可能是相关的。

在您的代码中,这可能有效:

Panel pnlChannel = GetDropDownList(); //returns a configured panel with controls.
pnlChannel.Location = new Point(56,72); //Should not be required
pnlChannel.Size = new Size(264, 152); //Should not be required
pnlChannel.Visible=true; //(Or sometimes Show(), depending).

你知道是否必须在某处添加面板吗?抱歉,我的exp基于WinForms,不是必需的。