Scott Chang

Hi all,

1) The following code worked in one Windows Application (named "VB ExpressDB-1") nicely without any problems:

Imports System.Data

Imports System.Data.SqlClient

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim cnn1 As SqlConnection

Dim cmd1 As SqlCommand

cnn1 = New SqlConnection("server=.\SQLEXPRESS;Trusted_Connection=yes;database=ssmsExpressDB")

cmd1 = New SqlCommand("SELECT * FROM LabTests", cnn1)

Try

cnn1.Open()

cmd1.CommandText = "SELECT Result FROM LabTests WHERE AnalyteID='23'"

cmd1.Connection = cnn1

Me.Label1.Text = "6th AnalyteName: Trichloroethene & Its Conc : " & _

cmd1.ExecuteScalar().ToString()

Catch ex As Exception

Me.Label2.Text = "ex.Message"

Finally

cnn1.Close()

Me.Label3.Text = "Connection: cnn1 is Closed."

End Try

End Sub

End Class

////////////////////////////////////////////////////////////////////

2) However, the following code (named "VBExpressDB-2) that is similar to the above code gave me an Exception:

Imports System.Data

Imports System.Data.SqlClient

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim cnn As SqlConnection

Dim cmd As SqlCommand

cnn = New SqlConnection

("server=.\SQLEXPRESS;Trusted_Connection=yes;database=ssmsExpressDB")

cmd = New SqlCommand("SELECT * FROM LabTests", cnn)

cnn.Open()

cnn.Open()

cmd.CommandText = "SELECT Result FROM LabTests WHERE AnalyteID='3'"

cmd.Connection = cnn

Me.Label1.Text = "1st AnalyteName: Trichloroethene & Its Conc : " & _

cmd.ExecuteScalar().ToString()

Catch ex As Exception

Me.Label3.Text = "ex.Message"

Finally

cnn.Close()

Me.Label4.Text = "Connection: cnn is Closed."

End Try

cnn.Close()

End Sub

End Class

////////////////////////////////////////////////////////////////////////

I do not know why the 2nd set of source code did not work. Please help and advise.

Thanks,

Scott Chang




Re: .NET Framework Data Access and Storage Exception in SqlConnection & SqlCommand of ADO.NET 2.0 & VB 2005 Express Form

Hayder Marzouk

Hi,

The only difference i see that u are opening twice the connection :

cnn.Open()

cnn.Open()

If it does not resolve the problem send the error message u have.

HTH.





Re: .NET Framework Data Access and Storage Exception in SqlConnection & SqlCommand of ADO.NET 2.0 & VB 2005 Express Form

Scott Chang

Thanks, Hayder. It works perfectly, after deleting one "cnn.Open()". Scott Chang