C# 将DropDownList绑定到ListItemCollection,并且该值未添加到DDL

C# 将DropDownList绑定到ListItemCollection,并且该值未添加到DDL,c#,html,drop-down-menu,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

我在商务舱里有这个代码

    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;
    }
我从刀上取回了桌子,没有问题。我看着文本和值属性正确地填充(+1表示一些非常棒的文盲?),然后返回到演示文稿,我像这样绑定

 Helper helper = new Helper();
 ListItemCollection agentList = helper.GetAllAgents();
 agentList.Insert(0,"");
 this.ddlAgent.DataSource = agentList;
 this.ddlAgent.DataBind();
<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.SelectedValue
我希望看到代理id,但是我得到的是文本(代理名称),所以我尝试了这个

this.ddlAgent.SelectedItem.Value
但我得到了同样的结果。然后我看了一下正在生成的html源代码,它是这样的

 Helper helper = new Helper();
 ListItemCollection agentList = helper.GetAllAgents();
 agentList.Insert(0,"");
 this.ddlAgent.DataSource = agentList;
 this.ddlAgent.DataBind();
<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能够计算出它应该使用
文本
属性。

如果agentList是一个ListItemCollection,则以下代码对我有效,而无需调用此.ddlAgent.DataBind()

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

您需要指定DropDownList应该使用哪些字段作为文本和值。它看起来像是自动完成的(创建新ListItem的参数也被称为value和text),但它必须是显式的。