Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 749
  • Last Modified:

Open .MDF Sql sever connection VB.Net


I'm building a windows forms application  in Visual Studio 2008.  I've set-up a SQL server 2008 .MDF database and attached it to my project. All the data is stored, used, shown etc and seems to work fine.

However, when I debug the project (for the first time!) or publish it I get a' timeout expired' error.

I think it is becuase I haven't explicity opened the connection to the database in code.

If I check the .MDF properties before and after I manually click the database in the Server Explorer,  I can see that the database properies 'State' changes from closed to open and then I don't get the error. However, I need to fix for publishing.

How do I open this connection in VB.Net?     (  .Net 3.5  )

2 Solutions
Sreedhar VengalaSr. Consultant - Business IntelligenceCommented:
If you are looking to obtain the state of an SQL connection before you open it you can use this if statement:
you can do :
If sqlConnection.State = ConnectionState.Closed Then
End IfIf sqlConnection.State = ConnectionState.Closed Then
End If

Open in new window

Hi dave,

Have a look at the following:

Good Luck!

davecocksAuthor Commented:
Hi thanks both of you for your help. I've split the points and I hope everyone is ok with the split. I used both the code from sree ven and the reference from Gary to track down a soltuion:

'Opens SQL connection
        'Prevents the timeout exception error
        'I put it on the load of each form
        Dim cn As New SqlClient.SqlConnection(My.Settings.internalConnectionString)
        If cn.State = ConnectionState.Broken OrElse cn.State = ConnectionState.Closed Then
            'reopen your connection:
        End If

PS. the database was called 'internal.mdf'

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now