c# - 将 DropDownList 绑定(bind)到 ListItemCollection 并且值未添加到 DDL

标签 c# html drop-down-menu

我在商务舱里有这段代码。

    internal ListItemCollection GetAllAgents()
    {
        DataTable table = dao.GetAllAgents();
        ListItemCollection list = new ListItemCollection();

        foreach (DataRow row in table.Rows)
        {
            list.Add(new ListItem(row["agent_name"].ToString(), row["id"].ToString()));
        }
        return list;
    }

我毫无问题地从 dao 取回了表。我看到 text 和 values 属性正确填充(+1 对于一些很棒的文盲?)并返回到演示文稿,我像这样绑定(bind)

 Helper helper = new Helper();
 ListItemCollection agentList = helper.GetAllAgents();
 agentList.Insert(0,"");
 this.ddlAgent.DataSource = agentList;
 this.ddlAgent.DataBind();

当我获取选定的值时

this.ddlAgent.SelectedValue

我希望看到代理 ID,但我得到的是文本(代理名称),所以我尝试了这个

this.ddlAgent.SelectedItem.Value

但我得到了相同的结果。然后我查看了正在生成的 html 源代码,它看起来像这样

<select name="ctl00$ContentPlaceHolder1$ddlAgent" onchange="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$ddlAgent\',\'\')', 0)" id="ctl00_ContentPlaceHolder1_ddlAgent">
        <option selected="selected" value=""></option>
        <option value="agent1_name">agent1_name</option>
        <option value="agent2_name">agent2_name</option>

此模式适用于所有代理。我希望我只是在做一些愚蠢的事情,你们可以在解决我的问题时窃笑 :)

谢谢大家。

编辑如果我这样做

ListItemCollection agentList = helper.GetAllAgents();
agentList.Insert(0,"");
foreach (ListItem agent in agentList)
{
    this.ddlAgent.Items.Add(agent);
}

它工作正常。

最佳答案

尝试做:

this.ddlAgent.DataTextField = "Text";
this.ddlAgent.DataValueField = "Value";
this.ddlAgent.DataSource = agentList;
this.ddlAgent.DataBind();

应该也可以,而且它可能比无缘无故地遍历列表要好。

更新找到了另一种(更短的)方法:

this.ddlAgent.Items.AddRange(agentList.ToArray());
this.ddlAgent.DataBind();

通过使用 Items.AddRange() 而不是使用 DataSource 设置源,ASP 能够确定它应该使用 TextValue 属性。

关于c# - 将 DropDownList 绑定(bind)到 ListItemCollection 并且值未添加到 DDL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161000/

相关文章:

c# - 使用 JSON 结果返回多个对象

javascript - transitionend 事件错误无法正确删除 CSS 类

php - 如何在不刷新页面的情况下发送表单?

twitter-bootstrap - 选择的下拉列表不适用于模态

CSS 下拉菜单悬停

c# - 通过回发保留 UpdatePanel 中 DIV 的滚动位置

c# - 使用 SQLCeResultSet 更新/插入表

C# 如何等待返回 Task<dynamic> 的方法?

javascript - 背景图片未覆盖整个网页

html - CSS下拉菜单: What is the fastest selector?