SqlException.ToString Method

Definition

Returns a string that represents the current SqlException object, and includes the client connection ID (for more information, see ClientConnectionId).

C#
public override string ToString();

Returns

A string that represents the current SqlException object.String.

Examples

The following C# example shows how a connection attempt to a valid server but non-existent database causes a SqlException, which includes the client connection ID:

C#
using System.Data.SqlClient;  
using System;  

public class A {  
   public static void Main() {  
      SqlConnection connection = new SqlConnection();  
      connection.ConnectionString = "Data Source=a_valid_server;Initial Catalog=Northwinda;Integrated Security=true";  
      try {  
         connection.Open();  
      }  
      catch (SqlException p) {  
         Console.WriteLine("{0}", p.ClientConnectionId);  
         Console.WriteLine("{0}", p.ToString());  
      }  
      connection.Close();  
   }  
}  

The following Visual Basic sample is functionally equivalent to the previous (C#) sample:

VB
Imports System.Data.SqlClient  
Imports System  

Module Module1  

    Sub Main()  
        Dim connection As New SqlConnection()  
        connection.ConnectionString = "Data Source=a_valid_server;Initial Catalog=Northwinda;Integrated Security=true"  
        Try  
            connection.Open()  
        Catch p As SqlException  
            Console.WriteLine("{0}", p.ClientConnectionId)  
            Console.WriteLine("{0}", p.ToString())  
        End Try  
        connection.Close()  
    End Sub  

End Module  

Applies to

Product Versions
.NET Core 1.0, Core 1.1, 6 (package-provided), 7 (package-provided), 8 (package-provided), 9 (package-provided), 10 (package-provided)
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)