I have written the following code in a class as my connection string. I want to retrive data from a field in a table in my database using this connecyion string. Please how do i go about it?

Public Class ConnectionString
    
    Public Shared Function ConnSQL() As SqlConnection
        Dim connectionString As String
        Dim cnn As SqlConnection
        connectionString = " initial catalog=dbase; Data Source=localhost; User Id=user; Password=pass"
        cnn = New SqlConnection(connectionString)
        Try
            cnn.Open()

        Catch ex As Exception
            MsgBox("Cannot open connection ! ")
        Finally
            cnn.Close()
        End Try
        Return cnn
    End Function

End Class

You could always change your code to be:

Catch ex As Exception
MsgBox(ex.Message)
Finally

to actually see what exception is being caught.

You could always change your code to be:

Catch ex As Exception
MsgBox(ex.Message)
Finally

to actually see what exception is being caught.

The Structured error sysntax is very okay. I just need the codes to return selected dataset using the connection string in the class

Oh I see. If you want to return a lot of data use a dataadapter

SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "Your sql statement";
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);

You can remove you cnn.Open() and cnn.Close() as the DataAdapter takes care of that itself. You end up with the data you extracted from the database in the dataTable.

Hope that helps.

Thanks you guys. Already solved it. My codes were very okay just that i forgot to add codes to bind my controls to the dataset.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.