App.config
<add name="databaseName" connectionString="Data Source=localhost; Initial Catalog=ABC_DB; Persist Security Info=True; User ID=sa;Password=1234"/>
Window.xaml.cs
public MainWindow()
{
InitializeComponent();
OpenConnection();
}
public SqlConnection con = new SqlConnection
{
ConnectionString = ConfigurationManager.ConnectionStrings["databaseName"].ConnectionString
};
public void OpenConnection()
{
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
/// If you want the program to exit completely
/// Environment.Exit(0);
}
}
Additional, you can add something like this:
public void Whatever()
{
if (con.State == ConnectionState.Open)
{
/// Your code
}
else
{
MessageBox.Show("Could not connect to server", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
OpenConnection();
}
}