hi everyone,
is there any way that I can programatically tell the user weather he/she is successfully connected to the database(SQL Server 2005). or connection failed.
Code is written in C#.

string Connectionstring = "....";
sqlConnection con = new sqlConnection(Conncetionstring);
con.Open();

how I can check programatically weather con.Open() is sucess of failed.

Dani AI

Generated

Good start: @kvpraj456 asked how to tell if a SQL Server connection succeeded, and and are right to point toward exception handling. Below is a concise, safer pattern that builds on that advice: it disposes the connection reliably, avoids blocking UI threads if you use the async version, checks the connection state, and captures diagnostic details for logging while keeping user-facing messages friendly.

using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

async Task<bool> CanConnectAsync(string connectionString)
{
    try
    {
        using (var conn = new SqlConnection(connectionString))
        {
            await conn.OpenAsync();
            return conn.State == ConnectionState.Open;
        }
    }
    catch (SqlException ex)
    {
        // log ex.Number and ex.Errors (do not show raw DB error to users)
    }
    catch (InvalidOperationException ex)
    {
        // log ex.Message
    }
    catch
    {
        // log unexpected problems
    }
    return false;
}

Why this helps: using ensures the connection is closed/disposed even on failure; OpenAsync prevents UI freezes in async contexts; checking conn.State verifies the connection is open after OpenAsync/Open. Inspect SqlException properties (for example Number and the Errors collection) to classify failures and log meaningful diagnostics without exposing internal details to end users. See the ADO.NET docs for SqlConnection.Open and SqlException.

Quick troubleshooting tips: verify the connection string with SqlConnectionStringBuilder, ensure SQL Server allows remote connections, confirm authentication mode and credentials, check firewall/port and named-instance syntax, and set a reasonable connection timeout. For intermittent network/transient failures add a retry policy (e.g., Polly) rather than repeatedly surfacing errors to users.

Recommended Answers

All 2 Replies

Use try..catch..finally block.

You can use like this,

string Connectionstring = "....";
sqlConnection con = new sqlConnection(Conncetionstring);
try
        {
            con .Open();
        }
        catch (SqlException exp)
        {
//assigned into string vari
            strErrorState = exp.Message;
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.