Thursday, December 06, 2007

ASP.NET DropDownList and SortedList Problems

In my computer-geek day job I'm working on a logistical system for our transportation department. Part of this application is to administer data on the driving teams. Each team consists of two drivers and a tractor rig.

I set up the first page in the application to list all the teams and sort them by various criteria such as last names, seniority date or tractor number. Then, one can click on a link and be sent to the page where a particular team's information can be edited.

The drivers are assigned to a team as either a senior driver or a junior driver. Since a senior driver can be moved into a junior driver spot and vice-versa for the junior driver, I created 2 drop down lists so the administrator can pick and choose which driver goes into which spot. I also created a method to get a sorted list with the drivers' names and numbers to populate the drop down lists. As the lists are filled, the app checks the actual team data and pre-selects the two drivers' names in the list.

Sounds simple enough. The code was something like this (in C# - it's similar in VB.NET):

int keepCount = 1;
ddlSenior_Driver.Items.Insert(0, "Select Driver");
ddlOther_Driver.Items.Insert(0, "Select Driver");
foreach (DictionaryEntry q in driverSortedList)
ListItem w = new ListItem();
w.Text = q.Key.ToString();
w.Value = q.Value.ToString();
ddlSenior_Driver.Items.Insert(keepCount, w);
if (w.Value.ToString() == teamData[1].ToString())
{ ddlSenior_Driver.SelectedValue = teamData[1].ToString(); }
ddlOther_Driver.Items.Insert(keepCount, w);
if (w.Value.ToString() == teamData[2].ToString())
{ ddlOtherDriver.SelectedValue = teamData[2].ToString(); }

When I ran that code, the selected driver in both lists was the same person, the person in the team array which was the Other Driver. Strange.

I double-checked the data, the array data, the method which pulled the data from the database. Everything checked out. I even had a colleague look at the code to see if I missed something. Everything was set up correct as far as we could see.

So, in desperation I set up the Other Driver drop list to get its data from another sorted list. I set up the sorted list and made it equal to driverSortedList. Once I did that, everything worked as I expected.

I don't know if this is a bug, "feature" or just a quirk in the .NET Framework. But, here it is just in case someone else has the same problem. Perhaps this will save someone some aggravation.

No comments:

Post a Comment