How to know actual problem because of which SqlException is thrown?

Try something like this, this will help you in handling different conditions.

use a try catch block like this:

try    
{
  ...
  ...
}
catch (SqlException ex)
{
  switch (ex.Number) 
    { 
        case 4060: // Invalid Database 
                  ....
                  break;

        case 18456: // Login Failed 

                  ....

                  break;

        case 547: // ForeignKey Violation 

                  ....

                  break;

        case 2627: 
                // Unique Index/ Primary key Violation/ Constriant Violation 

                  ....

                  break;

        case 2601: // Unique Index/Constriant Violation 

                  ....

                  break;

        default: 

                  ....

                  break;    

       } 
}

Leave a Comment