Reputation: 341
I have the following connection string class
Imports System.Data.SqlClient
Public Class DBConnection
Sub GetConnection()
Dim CrmsConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)
End Sub
End Class
And I have tried to call the connection string from the above class as follows:
Dim dbcon As DBConnection
Dim con As New SqlConnection(dbcon.GetConnection())
But it has an error near dbcon.GetConnection(). What is the solution?
Upvotes: 1
Views: 113
Reputation: 216343
GetConnection is a sub. This means that it doesn't return anything and you cannot try to use an inexistant return value. (This is a compile time error, you can't produce any executable code until you fix it)
Make it a function and public
Public Function GetConnection() as SqlConnection
return New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)
End Function
and then use it as (but create the class instance first otherwise a null reference exception occurs at runtime)
' Create the instance of the DBConnection class and ...
Dim dbcon As DBConnection = new DBConnection()
' ... get the connection
Dim con as SqlConnection = dbcon.GetConnection()
Finally remember to use the Using statement around disposable objects like this
Using con = dbCon.GetConnection()
....
End Using
Upvotes: 1