0

I need to retrieve the "id" from datasource of the selected item, but it always throws the same error mentionned in the title. Here is my code

        Dim DMV As DataRowView = LbMCat.SelectedValue 'Here occurs the error
    SelectedMainCat = DMV.Item("id") 

    'Filling the SUB Categories part / same code used to fill Main categories
    Dim DataAdapterCats As New MySqlDataAdapter("SELECT * From catS where maincat = '" & SelectedMainCat & "';", MySqlConnection)
    Dim dsSc As New DataSet
    DataAdapterCats.Fill(dsSc, "SubCategories")
    Dim SDataTable As DataTable = dsSc.Tables(0)
    LbSCat.DataSource = SDataTable
    LbSCat.DisplayMember = "title"
    LbSCat.ValueMember = "id"
Chaibi Alaa
  • 83
  • 2
  • 12

3 Answers3

2

Do as below

Dim DMV As DataRowView = TryCast(LbMCat.SelectedItem, DataRowView)

If DMV IsNot Nothing Then
    SelectedMainCat = DMV.Item("id")
End If
Damith
  • 62,401
  • 13
  • 102
  • 153
0

Try to Direct Cast the value :

(DirectCast(LbmCat.SelectedItem, DataRowView)("ID").ToString())

See it here. It may help

Rajeev Bera
  • 2,021
  • 1
  • 16
  • 30
VB.NET LEARNER
  • 711
  • 5
  • 11
0

what if you check is the selected value is not integer??

If Not TypeOf (LbMCat.SelectedValue) Is Integer Then
    Dim DMV As DataRowView = LbMCat.SelectedValue 'Here occurs the error
    SelectedMainCat = DMV.Item("id")     
End If
Bibek Gautam
  • 581
  • 8
  • 30