我在商务舱里有这段代码。
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 能够确定它应该使用 Text
和 Value
属性。
关于c# - 将 DropDownList 绑定(bind)到 ListItemCollection 并且值未添加到 DDL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2161000/