Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use this code to connect to the SQL database. Where and how should I make the exception when the SQL server could not be reached?


private void BT_AanmeldenAanmelden_Click(object sender, EventArgs e)
{
    this.Cursor = Cursors.WaitCursor;

    using (connection = new SqlConnection(connectionstring))

    using (SqlDataAdapter adapter = new SqlDataAdapter("Select Count(*) From Users Where Email = '" + TX_AanmeldenGebruikersnaam.Text + "' and Wachtwoord = '" + TX_AanmeldenWachtwoord.Text + "'", connection))
    {
        DataTable dt = new DataTable();
        adapter.Fill(dt);

        if (dt.Rows[0][0].ToString() == "1")
        {
            Progres_Login.Visible = true;
            TimerLogin.Start();
            this.Cursor = Cursors.Default;
        }
        else
        {
            this.Cursor = Cursors.Default;
            MessageBox.Show("De door u ingevulde gebruikersnaam en wachtwoord zijn incorrect", "##**## | Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
    }
}
Posted
Comments
Tomas Takac 15-Dec-15 9:04am    
You don't need to. The exception will be thrown when connection is open which in your code happens in adapter.Fill().

1 solution

C#
try{
    adapter.Fill(dt);
}
catch (Exception exp)
{
    // do something
}


It's bad practice to catch "Exception" though, you can find out what specific exceptions are raised when SQL isn't available and catch those specifically to give a more targeted message.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900