I load cities from the data context into two different lists and bind them to their respective DropDownList controls.
Although the code is the same for both, and only the data and obviously the name of the controls are different, the data binding seems to not work properly for only one of them. Instead of displaying the city name, it displays its Id, that is, for the first option only!
We have two DropDownList controls:
DestinationDropDownList;OriginDropDownList.
Then, I populate them.
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" />
Data displayed:
*DestinationDropwDownList*
- 0000-0000-0000-0000-0000 (empty Guid)
- CityName 01
- CityName 02
- ...
*OriginDropDownList*
- - Select a city -
- CityName 01
- CityName 02
- ...
The correct display is the one rendered by OriginDropDownList control. Why is DestinationDropDownList not displaying the data correctly, that is, for the first and only the first item in its list?
- I tried removing the first item before inserting the instruction;
- I tried to insert the instruction twice, then remove the first one;
- I tried to go along with the
DropDownList.Items.Add(string)method, and this was displaying nothing as for the first row, instead the the empty Guid.
How can I correct this behaviour!?
I haven’t encountered this issue before, but I will try to answer your second question. I see little value in adding the first ‘instructional’ item through code (correct me if I’m wrong). I’d rather add it directly to the mark-up:
The first item will survive the data binding due to the use of the
AppendDataBoundItemsattribute. I also added theDataTextFieldandDataValueFieldattributes, you can remove those from the code as well.Another thing you can do before data binding, is projecting the entities to
ListIteminstances:This way, you don’t have to set the
DataTextFieldorDataValueFieldproperties on the control as you are already creating the list’s items yourself.