Ran_TH Ran_TH - 1 month ago 23
Vb.net Question

Read data from JSON array to datasource

I have following data from a JSON file that I would like to add as a Datasource for a Combobox in a form:

"opr": [
{
"name": "John",
"code": "JS"
},
{
"name": "Diana",
"code": "DC"
},
{
"name": "Cashier",
"code": "CS"
}
],


"name" is a string that I'd like to display in the form, whereas "code" is the contained value to each name (say if I pick John, then "JS" will display in another text box")

Here's the class I'm going to use:

Public Class Opr
Public Property name As String
Public Property code As String
End Class

Public Class cgOpr
Public Property opr As Opr()
End Class


Previously I've used For Each to iterate through all IDs and add them with Items.Add, but I wonder if I can use Datasource for this. To my understanding I need to convert the array to a list but I haven't figured out how.

I'm using JSON.NET for parser. Thank you in advance.

Answer Source

You can use array as datasource too.

Dim data As cgOpr = JsonConvert.DeserializeObject(Of cgOpr)(jsonString)

combobox.ValueMember = "code"
combobox.DisplayMember = "name"
combobox.DataSource = data.opr

Then you can use combobox.SelectedItem or combobox.SelectedValue for accessing selected data

Dim selected As Opr = DirectCast(combobox.SelectedItem, Opr)
Dim selectedCode As String = selected.code

' Or
Dim selectedCode As String = combobox.SelectedValue.ToString()