【发布时间】:2012-02-18 23:15:06
【问题描述】:
我将数据上下文中的城市加载到两个不同的列表中,并将它们绑定到各自的 DropDownList 控件。
虽然两者的代码相同,只是数据和控件的名称不同,但数据绑定似乎只对其中一个不能正常工作。它不显示城市名称,而是显示其 Id,即仅针对第一个选项!
我们有两个 DropDownList 控件:
-
DestinationDropDownList; -
OriginDropDownList。
然后,我填充它们。
public partial class MyControl : UserControl {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
var instruction = new City() {
CityId = Guid.Empty,
CityName = "- Select a city -"
};
var destinations = context.Cities.ToList();
destinations = destinations.OrderBy(c => c.CityName).ToList();
destinations.Insert(0, instruction);
DestinationDropDownList.DataSource = destinations;
DestinationDropDownList.DataTextField = "CityName";
DestinationDropDownList.DataValueField = "CityId";
DestinationDropDownList.DataBind();
var origins = context.Cities.ToList();
origins = origins.OrderBy(c => c.CityName).ToList();
origins.Insert(0, instruction);
OriginDropDownList.DataSource = origins;
OriginDropDownList.DataTextField = "CityName";
OriginDropDownList.DataValueField = "CityId";
OriginDropDownList.DataBind();
}
}
private static readonly MyDataContext context = new MyDataContext();
}
HTML:
<asp:DropDownList ID="DestinationDropDownList" runat="server" />
<asp:DropDownList ID="OriginDropDownList" runat="server" />
显示的数据:
*DestinationDropwDownList*
- 0000-0000-0000-0000-0000 (empty Guid)
- CityName 01
- CityName 02
- ...
*OriginDropDownList*
- - Select a city -
- CityName 01
- CityName 02
- ...
正确的显示是由OriginDropDownList 控件呈现的。为什么DestinationDropDownList 没有正确显示数据,即列表中的第一个也是唯一的第一项?
- 我尝试在插入指令之前删除第一项;
- 我尝试插入指令两次,然后删除第一个;
- 我尝试使用
DropDownList.Items.Add(string)方法,但第一行没有显示任何内容,而是显示空的 Guid。
我该如何纠正这种行为!?
【问题讨论】:
-
我无法重现此问题...
-
JonH:我很高兴你不能这样做,因为当它发生时真是太痛苦了! ;) 谢谢你的一粒盐! =)
-
我只是不明白为什么会发生在你身上......
-
在
DestinationDropDownList.DataBind()上设置断点并调试您的应用程序。执行该行后,DestinationDropDownList.Items[0].Text的值是多少? -
Micheal:
DestinationDropDownList.Items[0].Text == "- Choisir -",所以显示应该没问题。另外,当我对其进行快速监视时,DestinationDropDownList.Text == Guid.Empty,这就是显示的内容,而不是实际选定的项目。有什么想法吗?
标签: asp.net data-binding webforms drop-down-menu