This documentation is archived and is not being maintained.

SqlCommand.Connection Property

Gets or sets the SqlConnection used by this instance of the SqlCommand.

Namespace: System.Data.SqlClient
Assembly: System.Data (in

Public Property Connection As SqlConnection
Dim instance As SqlCommand
Dim value As SqlConnection

value = instance.Connection

instance.Connection = value
/** @property */
public SqlConnection get_Connection ()

/** @property */
public void set_Connection (SqlConnection value)

public function get Connection () : SqlConnection

public function set Connection (value : SqlConnection)

Not applicable.

Property Value

The connection to a data source. The default value is a null reference (Nothing in Visual Basic).

Exception typeCondition


The Connection property was changed while a transaction was in progress.

If you set Connection while a transaction is in progress and the Transaction property is not null, an InvalidOperationException is generated. If the Transaction property is not null and the transaction has already been committed or rolled back, Transaction is set to null.

The following example creates a SqlCommand and sets some of its properties.

Public Sub CreateCommand(ByVal queryString As String, _
  ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand()
        command.Connection = connection
        command.CommandTimeout = 15
        command.CommandType = CommandType.Text
        command.CommandText = queryString

        Dim reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
            Console.WriteLine(String.Format("{0}, {1}", _
                reader(0), reader(1)))
        End While
    End Using
End Sub

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0