Rekcs Rekcs - 7 months ago 26
Vb.net Question

Link combobox with database values

I'm trying to link a ComboBox with Database values but after I debug it gave me an error related System.IndexOutOfRangeException. Here it is the following code that I'm using right now

SQLCon = New SqlConnection
SQLCon.ConnectionString = "..."
Try
SQLCon.Open()
Dim Query As String
Query = "SELECT Filetype FROM infofile GROUP BY Filetype"
SqlCmd = New SqlCommand(Query, SQLCon)
SQLDataReader = SqlCmd.ExecuteReader
While SQLDataReader.Read
Dim fileType = SQLDataReader.GetString(1)
ComboBox1.Items.Add(fileType)
End While
SQLCon.Close()
Catch ex As SqlException
MsgBox(ex.Message)
Finally
SQLCon.Dispose()
End Try


The error occurs
Dim fileType = SQLDataReader.GetString(1)


I know why this is happening, because if I use the
SELECT * FROM infofile
it works but I want to group it instead of displays all the data

Answer

GetString() takes a 0-based index number. You are asking it to give you the second element (index number 1) when you only selected one column. There is no second element. Change the 1 to a 0.

More info on the GetString method: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getstring%28v=vs.110%29.aspx