Home > Enterprise >  Retrieve Data from database and add on the item list of combobox
Retrieve Data from database and add on the item list of combobox

Time:01-25

Hi i could not get the error says invalid to convert to string

here is my code below

'open connection
        If Not conn.State = ConnectionState.Open Then
            conn.Open()
            ' MsgBox("connection open")
        End If
        '-------
        Dim da As New OleDb.OleDbDataAdapter("SELECT DISTINCT ItemDateEntry FROM Item", conn)
        Dim dt As New DataTable
        da.Fill(dt)

        For Each row As DataRow In dt.Rows

            DateYear.Items.Add(dt.Rows()("ItemDateEntry"))

        Next


'open connection
        If Not conn.State = ConnectionState.Open Then
            conn.Open()
            ' MsgBox("connection open")
        End If
        '-------
        Dim da As New OleDb.OleDbDataAdapter("SELECT DISTINCT ItemDateEntry FROM Item", conn)
        Dim dt As New DataTable
        da.Fill(dt)

        For Each row As DataRow In dt.Rows

            DateYear.Items.Add(dt.Rows()("ItemDateEntry").ToString)

        Next

I've tried adding ".ToString" but nothing works and nothing display on my combobox

CodePudding user response:

It looks like you don't know how For or For Each loops work, so you ought to spend some time getting a better grip on that. This:

DateYear.Items.Add(dt.Rows()("ItemDateEntry"))

should be this:

DateYear.Items.Add(row("ItemDateEntry"))

To elaborate, the point of a For Each loop is to perform some action(s) for each item in a list. The For Each statement itself specifies the list and provides a variable for the current item. You have this:

For Each row As DataRow In dt.Rows

therefore row is your variable for the current item. If you're not using that variable inside the loop, you're almost definitely doing something wrong.

If you were using a For loop instead then you'd have this:

For i = 0 To dt.Rows.Count - 1

and then you'd have to use i in the loop to get an item. That would mean using code that looked something like what you had originally:

DateYear.Items.Add(dt.Rows(i)("ItemDateEntry"))

That said, just bind the data:

DateYear.DisplayMember = "ItemDateEntry"
DataYear.DataSource = dt

You can then use the Text property of the ComboBox to get thetext displayed for the SelectedItem. If you want something other than that String, you can also set the ValueMember to the name of the appropriate column and then get the SelectedValue. That will be type Object, so you can cast it as whatever type the underlying value is.

  • Related