How to handle ValueMember

PatelNehal4u

Active member
Joined
Apr 6, 2009
Messages
25
Programming Experience
1-3
i m using visual basic 2008 and in winform lstCity is the listbox which handle the city names as Displaymember and id as value member, now when i select any city from the lstcity by keypress(enter) i m getting the maximum valuemember everytime so is there any way to retrieve the valuemember of selectedindex.

************************************************
Private Sub PopulateListbox()
If ds.Tables(0).Rows.Count > 0 Then
lstCity.Visible = True
lstCity.Items.Clear()
lstCity.BringToFront()
'populate all the city name in listbox
For Each udr As DataRow In ds.Tables(0).Rows()
lstCity.Items.Add(udr.Item(1))
lstCity.ValueMember = udr.Item(0)
lstCity.DisplayMember = udr.Item(1)
Next
lstCity.Focus()
lstCity.SelectedIndex = 0
Else
'the database is empty
End If
End Sub
****************************************************
Private Sub lstCity_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles lstCity.KeyDown
Dim cid As Integer
If e.KeyCode = Keys.Enter Then
cid = CType(lstCity.ValueMember, Integer)
lstCity.Visible = False
ShowByCityID(cid)
End If
End Sub
****************************************************
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,493
Location
Sydney, Australia
Programming Experience
10+
You are going about this all wrong. This:
VB.NET:
For Each udr As DataRow In ds.Tables(0).Rows()
lstCity.Items.Add(udr.Item(1))
lstCity.ValueMember = udr.Item(0)
lstCity.DisplayMember = udr.Item(1)
Next
should be this:
VB.NET:
lstCity.DisplayMember = "CityName"
lstCity.ValueMember = "CityID"
lstCity.DataSource = ds.Tables(0)
and this:
VB.NET:
cid = CType(lstCity.ValueMember, Integer)
should be this:
VB.NET:
cid = CType(lstCity.SelectedValue, Integer)
If your columns are not named "CityName" and "CityID" then substitute the appropriate values.
 
Top Bottom