Share via


SqlErrorCollection.Item[Int32] Property

Definition

Gets the error at the specified index.

public:
 property Microsoft::Data::SqlClient::SqlError ^ default[int] { Microsoft::Data::SqlClient::SqlError ^ get(int index); };
public Microsoft.Data.SqlClient.SqlError this[int index] { get; }
member this.Item(int) : Microsoft.Data.SqlClient.SqlError
Default Public ReadOnly Property Item(index As Integer) As SqlError

Parameters

index
Int32

The zero-based index of the error to retrieve.

Property Value

A SqlError that contains the error at the specified index.

Exceptions

Index parameter is outside array bounds.

Examples

The following example displays each SqlError within the SqlErrorCollection collection.

using Microsoft.Data.SqlClient;
using System.Text;

class Program
{
    static void Main()
    {
        string s = GetConnectionString();
        ShowSqlException(s);
        Console.ReadLine();
    }
    public static void ShowSqlException(string connectionString)
    {
        string queryString = "EXECUTE NonExistantStoredProcedure";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            try
            {
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                DisplaySqlErrors(ex);
            }
        }
    }

    private static void DisplaySqlErrors(SqlException exception)
    {
        for (int i = 0; i < exception.Errors.Count; i++)
        {
            Console.WriteLine("Index #" + i + "\n" +
                "Error: " + exception.Errors[i].ToString() + "\n");
        }
        Console.ReadLine();
    }

    static private string GetConnectionString()
    {
        // To avoid storing the connection string in your code, 
        // you can retrieve it from a configuration file.
        return "Data Source=(local);Initial Catalog=AdventureWorks;"
            + "Integrated Security=SSPI";
    }
}

Applies to

See also