Question

Im having a problem when trying to run my code. Im new to stackoverflow but will try to explain my problem.

Well, i get a "InvalidCastExeption" with the explanation

"Converson from string "Filename" to type "Integer" is not valid.

The confusing part is that FileName is a nvarchar(30) in my SQL database, and sName a string.

Look at the code, it failes at the dim sName = ... Ps - I have tried to convert.toint / Cint, but it doesnt help. AND i want it as a string, not a integer!

Imports System
Imports System.Data
Imports System.Data.SqlClient

Public Class SelectrecipieDatabaseManager
    Private Const CONNECTION_STRING As String = "Data Source=RYOW701;Initial Catalog=RyReci;Integrated Security=True"
    Private connection As SqlConnection = Nothing
    Private command As SqlCommand = Nothing

    Public Sub RecipieHandler(ByVal Choice As String)

        Dim reader As SqlDataReader
        connection = New SqlConnection(CONNECTION_STRING)

        Try
            connection.Open()


                Dim Query As String
                Query = "select *  from TbNew"
                command = New SqlCommand(Query, connection)
                reader = command.ExecuteReader

                While reader.Read

                    Dim sName = reader.GetString("FileName")

                    RecipieForm.ComboBoxRec.Items.Add(sName)
                End While



        Catch ex As SqlException
            MessageBox.Show(ex.Message)

        Finally
            connection.Close()
            connection.Dispose()
        End Try

    End Sub

End Class
Was it helpful?

Solution

The getString method expects an ordinal number as it's parameter, not a string. Do this instead:

reader = command.ExecuteReader
Dim columnID As Integer = reader.GetOrdinal("FileName")

While reader.Read
    Dim sName = reader.GetString(columnID)
    RecipieForm.ComboBoxRec.Items.Add(sName)
End While
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top