如何在网页表单中加载页面之前填充下拉列表? [英] How to populate dropdown list before page loads in webforms?

查看:24
本文介绍了如何在网页表单中加载页面之前填充下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控件 (System.Web.UI.UserControl) 中有以下 Page_Load 方法:

I have the following Page_Load method in my control (System.Web.UI.UserControl):

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList ShowAssumptions = new DropDownList();
    List<string> list = new List<string>()
    {
        "test",
        "test2"
    };
    ShowAssumptions.DataSource = from i in list
                                 select new ListItem()
                                 {
                                     Text = i,
                                     Value = i
                                 };
    ShowAssumptions.DataBind();
}

然后,在我的 .aspx 中,我有这个:

Then, in my .aspx I have this:

<asp:DropDownList id="ShowAssumptions" runat="server">
</asp:DropDownList>

但是,DropDownList 永远不会被填充.我做错了什么?

But, the DropDownList never gets populated. What am I doing wrong?

推荐答案

只需将列表指定为数据源即可.此外,我假设您不想在每次回发时重新加载列表.

Just assign the list as the datasource. Also I assume you don't want to reload the list on every PostBack.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         List<string> list = new List<string>()
         {
            "test",
            "test2"
         };
        ShowAssumptions.DataSource = list;
        ShowAssumptions.DataBind();
    }
}

这篇关于如何在网页表单中加载页面之前填充下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆