Hi,
I am quite new to ASP.NET but I think I'm managing so far. I have now come across an odd problem that I can't seem to solve on my own...
I have a DropdownList control on a page where the user has to select a car. The available cars come from a database, and I am loading them into a List(Of Car), where Car is a simple class with four properties (Id, Team, Engine, Type), one readonly property that returns the text representation (so I can change this easily):
vb.net Code:
Public Class Car Public Sub New(ByVal id As Integer, ByVal team As String, ByVal engine As String, ByVal type As String) Me.Id = id Me.Team = team Me.Engine = engine Me.Type = type End Sub Public Property Id As Integer Public Property Team As String Public Property Engine As String Public Property Type As String Public ReadOnly Property Text Get Return String.Format("{0} {1} ({2})", Me.Team, Me.Type, Me.Engine) End Get End Property Public Overrides Function ToString() As String Return Me.Text End Function End Class
Now in the Page_Load event I call the LoadCars method which fills the DropdownList:
The CarManager.Load method merely loads all cars from the database into a List(Of Car). As you can see, I set the DataTextField to "Text" (so that it uses the text representation of my choice) and the DataValueField to "Id", so that the actual values are the Id's of the cars.vb.net Code:
Private Sub LoadCars() Dim carManager As New CarManager Dim cars As List(Of Car) = carManager.Load() cboCars.DataSource = cars cboCars.DataTextField = "Text" cboCars.DataValueField = "Id" cboCars.DataBind() cboCars.SelectedIndex = 0 End Sub
In normal VB.NET (winforms) I would now expect the DropdownList to actually hold instances of the Car class, and that I can get the selected instance by using
But it seems this doesn't work that way in ASP.NET. The SelectedItem is a ListItem which cannot be cast to a Car.vb.net Code:
Dim car = DirectCast(cboCars.SelectedItem, Car)
Ok, that's a bit of a setback, but no worries, I can still get the Id via the SeletedValue property. Or so I thought... Apparently not
I would expect the SelectedValue property to return the value of the field I set as the DataValueField. This way I can still get the selected Car by loading it by Id:
Since I set the DataValueField to "Id" I would expect the SelectedValue to hold the Id of my Car.vb.net Code:
Dim car = carManager.LoadById(CInt(cboCars.SelectedValue))
But, for some reason, the SelectedValue is always "1" (the string "1", not an integer even). I've no idea why this happens. The Id property of my cars are not all 1, they go from 0 to 19. Yet, the SelectedValue always returns "1" and I keep getting the same car back no matter which I select.
What's going on, and how do I retrieve either the instance of the Car in the dropdown, or the Id of that instance if that is impossible directly?
Thanks!





Reply With Quote