locked
Cannot get SQLClient catch to work at catching exception RRS feed

  • Question

  • I am new to csharp.  I have some code that is working, but want to start working on exception handling.
    using System.Data.SqlClient;

    The first thing I am trying to trap for is if the SQL server is down, but the Catch just won't work.. I can't figure out why ... Any clues ?

    SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader rdr = null;
    
            try
            {
              // Open the connection and create a SQL command
              // TODO : I am having problems CATCHING the error here
    
    
              conn = new SqlConnection(connectString);
              conn.Open();
    
            }
            
            catch (SqlException ex)
            {
              string str;
              str = "Source:" + ex.Source;
              str += "\n" + "Message:" + ex.Message;
              Console.WriteLine(str, "Database Exception");
            }
                   
    

    When it hits conn.open(); and the server is running, life is good.

    If the server is down, it does not catch the exception but instead comes to the standard error trapping.. .It's driving me nuts, because the error message from vs actually says it's coming from

    {System.Data.SqlClient.SqlException}

    Any clues ?

     

    Sunday, October 3, 2010 5:52 PM

Answers

  • My guess on what's happening?  You're running this in the debugger, right?  So you're getting a 'first-chance' exception, and the code is stopping there, because Visual Studio is configured to immediately stop on First-Chance exceptions.

     

    Try this:  Click on Debug->Exceptions

    In the window that pops up, you should see a list of exception types, and two columns of check-boxes: Thrown and User-Handled.

    I'm guessing that, under the "Common Language Runtime Exceptions", both the Thrown and User Handled check-boxes are checked.

    You can do one of two things: 

    1. Set a breakpoint on your exception handler hit F5 (Continue) when that exception occurs, and your BP should be hit.

    2. Uncheck 'Thrown' in the Exceptions window above.  Note that if you do this, exceptions won't be shown AT ALL if they are caught in a try/catch.  If you're just testing or only hit the condition once or twice, I recommend #1.

     

    Phil

     

    • Proposed as answer by Mike Dos Zhang Monday, October 11, 2010 11:53 AM
    • Marked as answer by Mike Dos Zhang Tuesday, October 12, 2010 11:39 AM
    Wednesday, October 6, 2010 6:09 PM

All replies

  • Ok, hi,

    basically if it comes to the trapping , it seems you missed the exception , or the exception type such as , if you try to cacth an exception of

    integer parse of string while the exception in hand was "file was not found" , as you can see the are not related,

    as it seems you caught some execption that should be the same, could be the inner execption are not,

     

    my advise try :

    catach(exception ex)

    {//your code}

    and see what is the inner execption or the execption,

     

    keep me posted.

     

     

    Sunday, October 3, 2010 6:24 PM
  • Hi, thanks
    I tried something simpler...

     try
            {
              // Open the connection and create a SQL command
              // TODO : I am having problems CATCHING the error here
    
    
              conn = new SqlConnection(connectString);
              conn.Open();
    
            }
            
            catch (Exception ex)
            {
              Console.WriteLine(ex.Message);
            }
    

    It still seems to not trap and ever attempt to execute the exception catch.
    I have even tried changing to Console.WriteLine("test");

    Here is the actual exception stack from the cut-paste buffer

    ...............

    System.Data.SqlClient.SqlException occurred

      Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

      Source=.Net SqlClient Data Provider

      ErrorCode=-2146232060

      Class=20

      LineNumber=0

      Number=2

      Server=""

      State=0

      StackTrace:

           at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)

           at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()

           at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)

           at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)

           at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)

           at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)

           at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)

           at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)

           at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)

           at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)

           at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)

           at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)

           at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)

           at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)

           at System.Data.SqlClient.SqlConnection.Open()

           at InvestmentTracker.DataTalker.getSimpleListfromDatabase(String dataQueryCommand) in D:\WorkSpace\InvestmentTracker\InvestmentTracker\DataTalker.cs:line 137

      InnerException: 

    .......
    I managed to get exception trapping to work with other things such as divide by zeros, etc... all the standard errors in all the examples, and understand the ability to do specific expections for specific events. 

    ?

    Sunday, October 3, 2010 7:45 PM
  • emm that intersting,

    ok i tried my self some magic , look all the depending objects on the connection will fail in the same reason -

    in my test the DataContext object gave the problem after the try and also in another test the adapter .

     

    try to see if you can tell me if after the Try statement something is using a DBConnection object-base ?

     

    regards.

    Sunday, October 3, 2010 8:24 PM
  • The code you've posted looks ok (and yes, you want to be catching the SqlException). Is there some other code which you have that you have not posted?
    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Sunday, October 3, 2010 9:12 PM
  • The original code caught SqlException and didn't work (the reason for my post).  I have it back at SqlException.

    Here's the whole class... I am having the problems in getSimpleListfromDatabase

    It works fine if the SQL server is running but not if it is not.

    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.ServiceProcess;
    using System.Windows;
    
    
    namespace InvestmentTracker
    {
      class DataTalker
      {
        
        private static string connectString = Properties.Settings.Default.myConnectionString;
    
        /// <summary>
        /// restartSQL restarts the local SQL service.. will be hardcoded to my machine for now
        /// </summary>
        /// <returns>true or false</returns>
        public void restartSQL()
        {
          string serviceName = "SQL Server (SQLEXPRESS)";
          
                
          
    
           ServiceController service = new ServiceController(serviceName);
           if (service.Status == ServiceControllerStatus.Running)
           {
             try
             {
               TimeSpan timeout = TimeSpan.FromMilliseconds(30000);
    
               service.Stop();
               service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
             }
             catch
             {
               // ...
             }
           }
    
           if (service.Status != ServiceControllerStatus.Running)
           {
             try
             {
               TimeSpan timeout = TimeSpan.FromMilliseconds(30000);
    
               service.Start();
               service.WaitForStatus(ServiceControllerStatus.Running, timeout);
             }
             catch
             {
               // ...
             }
           }
    
        }
    
        /// <summary>
        /// Received a simple SQL command and executes it.. returns "OK" or returns "FAIL"
        /// </summary>
        /// <param name="simpleSQLCommand"></param>
        /// <returns>'OK' or 'FAIL'</returns>
        public string SimpleSQLCommand(string simpleSQLCommand)
        {
          String fail = "FAIL";
          String result = "FAIL";
          
          if (simpleSQLCommand == null) { return fail; }
          if (simpleSQLCommand.Trim().Length == 0) { return fail; }
    
          SqlConnection conn = null;
          SqlCommand cmd = null;
    
          
            // Open the connection and create a SQL command
    
            conn = new SqlConnection(connectString);
            conn.Open();
    
          
          
          cmd = new SqlCommand();
    
          cmd.Connection = conn;
    
          cmd.CommandText = simpleSQLCommand;
    
          try
          {
            cmd.ExecuteNonQuery();
          }
    
          finally
          {
            cmd.Dispose();
          }
                      
    
          result = "OK";
          return result;
    
        }
    
        public List<string> getSimpleListfromDatabase(string dataQueryCommand) 
        
        {
            List<string> dataList = new List<string>();        
            dataList.Clear();
          
            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader rdr = null;
    
            try
            {
              // Open the connection and create a SQL command
              // TODO : I am having problems CATCHING the error here
              
              conn = new SqlConnection(connectString);
              conn.Open();
    
            }
            
            catch (SqlException ex)
            {
              Console.WriteLine(ex.Source.ToString());
            }
                    
             
            cmd = new SqlCommand();
    
            cmd.Connection = conn;
    
            cmd.CommandText = dataQueryCommand;
            try
            
            {
    
            rdr = cmd.ExecuteReader();
    
                // Iterate through the results
                           
    
                while (rdr.Read())
                {
    
                  dataList.Add(rdr["Institution"].ToString());
                  
                  
                }
    
                // Always dispose data readers and commands as soon as practicable
                //
    
                rdr.Close();
                cmd.Dispose();
              }
    
              finally
              {
    
                // Close the connection when no longer needed
                //
                rdr.Dispose();
                conn.Close();
                conn.Dispose();
                
                
            }
    
            
            return dataList;
    
                  
        }
    
        
    
      }
    
    
    }
      
    • Edited by Having Fun Sunday, October 3, 2010 10:48 PM Originally submitted wrong code
    Sunday, October 3, 2010 10:39 PM
  • Hmmm ... that looks ok too. Is there anything peculiar in the code where you instantiate that DataTalker class and call the getSimpleListfromDatabase() method? How about posting that too ...
    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Sunday, October 3, 2010 10:50 PM
  • In your CATCH block, try to use catch (Exception ex) instead of SqlException.

    Does the code catch the error now?

     

    Noam B.



    Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...
    • Proposed as answer by Noam B Monday, October 4, 2010 12:45 PM
    • Unproposed as answer by BonnieBMVP Monday, October 4, 2010 1:56 PM
    • Proposed as answer by Cor Ligthert Monday, October 4, 2010 3:12 PM
    • Unproposed as answer by BonnieBMVP Monday, October 4, 2010 3:30 PM
    Monday, October 4, 2010 7:16 AM
  • The SQLException is to catch SQL transact code errors.

    Simply use the Exception instead of that.

    If you want to do both (although there is no SQL code in your statement), then catch both.

     

     


    Success
    Cor
    Monday, October 4, 2010 7:43 AM
  • look basically it can if some where along the code there is an object using that connection and it faileds (and also uncatched),

     

    please try to see where , if you can't send me the complete code to see maybe i can .

     

    thanks and hope it will help.

    Monday, October 4, 2010 1:24 PM
  • Arrrggghhh! Don't you guys read? The OP says that he's tried it both ways ... catching the SQLException and just a plain old Exception and either way IT'S NOT BEING CAUGHT!

    I've asked him to post a little more code (the code where he's actually calling the method that should be catching the exception). Something else is going on here ...


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Monday, October 4, 2010 1:56 PM
  • as you said it looks ok but i bet something there is using it , say a data reader or even a datacontext object,

    he should post it.

    Monday, October 4, 2010 2:25 PM
  •     try
        {
         // Open the connection and create a SQL command
         // TODO : I am having problems CATCHING the error here
    
    
         conn = new SqlConnection(connectString);
         conn.Open();
    
        }
          
        catch (SqlException qex)
        {
         Console.WriteLine(qex.Message);
        } 
    
        catch (Exception ex)
        {
         Console.WriteLine(ex.Message);
        }
    
    It seems you have two kind of errros
    Success
    Cor
    Monday, October 4, 2010 3:19 PM
  • Arrrggghhh! Don't you guys read? The OP says that he's tried it both ways ... catching the SQLException and just a plain old Exception and either way IT'S NOT BEING CAUGHT!

    I've asked him to post a little more code (the code where he's actually calling the method that should be catching the exception). Something else is going on here ...


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
     Bonnie,

    Can you use threaded view or/and as you use a bridge replies to the correct thread parts?

    Now I have really to invest on what you are replying, as this message seems related to the message from Naom and me, but that I saw only later when I had seen your reply in a strange place not related to the question too which your question was related.



    Success
    Cor
    Monday, October 4, 2010 3:29 PM
  • COR!! HE ALREADY TRIED THAT ... THIS IS THE SECOND TIME I'VE SAID THIS! READ THE POSTS BEFORE YOU REPLY! THIS IS ALSO THE SECOND TIME YOU'VE SAID THE SAME THING (this time with code)!

    Sorry for the shouting ... have you forgotten to have your cuppa coffee today? ;0)


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Monday, October 4, 2010 3:30 PM
  • COR!! HE ALREADY TRIED THAT ... THIS IS THE SECOND TIME I'VE SAID THIS! READ THE POSTS BEFORE YOU REPLY! THIS IS ALSO THE SECOND TIME YOU'VE SAID THE SAME THING (this time with code)!

    Sorry for the shouting ... have you forgotten to have your cuppa coffee today? ;0)


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com

    No I've not done this the second time, and this is not already in this thread.

    This is a double catch in one try block. 

    I've seen only single try blocks (some with finally)

    There is no need to shout by the way.

    Is it not better that you let the OP decide, otherwise we can ask Microsoft if they create a Bonnie Berent forum.


    Success
    Cor
    Monday, October 4, 2010 3:34 PM
  • Sorry Cor ... not seeing all the posts at one time is one of the reasons I don't use the threaded view, but I can see your dilemma (I don't use the bridge). Perhaps in these forums it's best not to use a threaded view (it would be interesting to see how many people do and don't).
    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Monday, October 4, 2010 3:37 PM
  • Bonnie,

    Most who are expirienced forum members use threaded view, you can see that in the way they do their replies.

    It is in my idea from the developer forums exceptional that you as MVP don't use that. 

    The default is however non threaded view so new members don't use that.

    It had in past many bugs, but those are solved, however still many long time users are using non threaded view because of those bugs. 

     

     


    Success
    Cor
    Tuesday, October 5, 2010 7:34 AM
  • Hi everyone, sorry for the delay in responding.  I've been out on the road.

    I have tried catching SqlException, Exception and even BOTH as some have suggested (SqlException first and Exception second).  I've even tried them both the other way around.  I'm going to try and see if it only happens when I run in VS2010 or if it actually acts the same way as compiled code.

    For those of you that are interested, it will take me a few days to extract out enough code that I can safely post all the bits needed.   I am going to try and catch the exceptions in the CALLING Class some how and see if that helps.. I'm thinking if I can't catch it here, maybe the upstream can catch it . I got this idea from one of the posters above (BonnieB).

    I have to head out again for a few days so it'll take me a bit and I don't want it to see like I don't appreciate the help.. I just literally have about 2 minutes on a computer from the road.

    Thanks
    HavingFun

    Tuesday, October 5, 2010 11:36 AM
  • Cor,

    I am one of those long time users ... I've been on these forums since around 2003. Perhaps it was because of those early bugs with threaded views that I prefer not to use it. Or maybe it's because many people don't view the thread that way either since it's not the default and therefore I'm seeing the thread the way most users will see it.

    At any rate, you can see that the threaded view still causes problems, IMHO, so I will continue to use the flat view. I will, however, try to reply in a manner that might make more sense for those who *do* use the threaded view.


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Tuesday, October 5, 2010 3:55 PM
  • I am going to try and catch the exceptions in the CALLING Class some how and see if that helps.. I'm thinking if I can't catch it here, maybe the upstream can catch it . I got this idea from one of the posters above (BonnieB).

    I don't know if that will make too much difference (IOW, it really should be caught in the try/catch where you open the connection), but I was thinking more along the lines of something else being weird in your calling class.

    One more thing ... have you tried tracing this in the debugger and see what happens when you try to open the connection?


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Tuesday, October 5, 2010 4:03 PM
  • Having Fun,

    I all the time have the idea that you have somewhere else another piece of code which open a connection, do you really debug this code step by step and does it then jump over that block?

     


    Success
    Cor
    Tuesday, October 5, 2010 4:45 PM
  • Hi Having Fun,

    Welcome to MSDN Forums!

     

    I had tested your code you posted out, but it can give me the expected result. So I also think about the root cause is in the other place. And the error message you posted out also seems the expected message. Your code and your error message tell us that there’s no anything not right in the code. The try-catch block is also can be accessed when we turn off the sql service. And the application also can print out the message we placed in the catch statement. So would you mind to take a check of your project again and make sure if there’s a problem?

     

    I don’t know the other community members’ opinion on this thread, but I think the code you post out are all right and have not problems in, also the exception message can tell us you can access the catch statement.

     

    And I also hope guys can take a look at op’s code and the exception message op posted out, if I said is right. If no, please feel free to point out. Then we can correct our direction.

     

    If there’s anything unclear or I have misunderstood you, please feel free to let me know.

     

    Have a nice day!

    Mike

    *****************************************************

    [All-In-One Code Framework]

    Sample world! You will get more from this world!

    Welcome to the new world!

    Wednesday, October 6, 2010 8:36 AM
  • Wow, I'm amazed at all the people trying to help ! Thanks !

    Here is the latest code block (showing both catches).. It STILL aborts at the conn.open();... I'm new to the debugger so I'll see what I can do there. A few of you suggested posting the "calling" code as well, so I'll post that at the end of this message... kind of backwards I know, but seems to me to be an easier way to present it.

    List<string> dataList = new List<string>();        
            dataList.Clear();
          
            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader rdr = null;
    
            try
            {
         // Open the connection and create a SQL command
         // TODO : I am having problems CATCHING the error here
    
              conn = new SqlConnection(connectString);
              conn.Open();
    
            }
    
            catch (SqlException qex)
            {
              Console.WriteLine(qex.Message.ToString());
            }
    
            catch (Exception ex)
            {
              Console.WriteLine(ex.Message.ToString());
                    }
    
             
            cmd = new SqlCommand();
    
    
    The rest is unchanged
    

    And here are the appropriate bits from the "calling" Class.

    using System.Windows;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using System;
    using System.Configuration;
    
    
    namespace InvestmentTracker
    {
    
        
      /// <summary>
      /// Interaction logic for MainWindow.xaml
      /// </summary>
      /// 
     
    
      public partial class MainWindow : Window
     
      
      {
      
      string myName = "";
      
        /// <summary>
       /// loginuser holds login user class
       /// </summary>
         static public LoginUser loginuser = new LoginUser(); // Will contain default user
         // there is currently no data access in the above class.. hardcoded at present to some fixed login users.
        
        /// <summary>
        /// The Main Window
        /// </summary>
        public MainWindow()
    
        {
          
          InitializeComponent();
    
          loginuser.User = "";
    
                
          LoginWindow loginwindow = new LoginWindow();
          loginwindow.ShowDialog();
    
          myName = loginuser.User;
          
          // This form should come up after data is retrieved to fill in the initial list box of institutions.
    
          InstitutionEdit iform = new InstitutionEdit();
          iform.Title = myName;
    
          iform.Show();
          this.Visibility = System.Windows.Visibility.Visible;
    
          this.Close();
    
        }
    
          
     
    

    Here is the appropriate code snippets for InsitutionEdit (where the problem takes place).. well, it takes place in Datatalker.cs but this is the "calling " or instantiating class.

    using System.Windows;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using System;
    using System.Windows.Controls;
    using System.Configuration;
    using System.Collections.ObjectModel;
    using Visifire.Charts;
    using Visifire.Commons;
    using System.Linq;
    using System.Collections.Generic;
    
    namespace InvestmentTracker
    {
      /// <summary>
      /// Interaction logic for InstitutionEdit.xaml
      /// This class is the basic Intstitution Editing Form
      /// </summary>
      /// 
      public partial class InstitutionEdit : Window
      
       {
    
        // We want a chart that is public to the entire page to make changes and to save a lot of grief
    
        Chart chart = new Chart();
        Title title = new Title();
        DataSeries dataseries = new DataSeries();
        DataColumn datacolumn = new DataColumn();
        DataPoint datapoint = new DataPoint();
        Axis axis = new Axis();
    
        
        ObservableCollection<InvestmentData> _InvestmentCollection =
        new ObservableCollection<InvestmentData>();
    
        /// <summary>
        /// Institution Edit Method
        /// </summary>
        /// 
        public InstitutionEdit()
    
        {
          
    
          InitializeComponent();
          FillInstitutionListBox1();
          InitializeEmptyChart();
    
         
        }
    
        /// <summary>
        /// InvestmentCollection is used to populate investments select based on Institution Selected
        /// </summary>
        /// 
        public ObservableCollection<InvestmentData> InvestmentCollection
        { get { return _InvestmentCollection; } }
    
        
    
          private void FillInstitutionListBox1()
            {
             
              // clear the listbox first either way
              // let's also clear the InvestmentCollection
    
              listBox1.Items.Clear();
              _InvestmentCollection.Clear();
    
    
            // TODO: REPLACE WITH NEW CODE
            // THIS IS WHERE THE CODE IS CALLING DataTalker to bring up the error
            
    
            <strong> <span style="text-decoration:underline">DataTalker dt = new DataTalker();
            List<string> dataList = new List<string>();
            dataList = dt.getSimpleListfromDatabase("Select Institution from Institutions ORDER BY Institution");</span></strong>
    
             // Iterate through the results
            int looper = 0;
            
                while (looper != dataList.Count)
    
                {
                  
                  listBox1.Items.Add(dataList[looper]);
                  looper = looper + 1;
    
                  
                }
    
                
            }
    

    I have underlined the code which starts up datatalker.cs and where datatalker.cs has an error if the sql server is down.  The exception from the debugger says it is in SqlException .. On the weekend I am going to try JUST the datatalker.cs by itself in it's own class to see if there is some kind of weird environment thing going on, but in the mean time, I thought I'd try another post here for those that are trying to help or interested... thanks

     

    Wednesday, October 6, 2010 11:14 AM
  • Wow, I don't see anything obviously wrong. I guess you're going to have to bite the bullet and try debugging (BTW, that's always the first thing I try, so it's good to know how to do it). Just set a breakpoint on the .Open() statement and see what happens when you execute that statement (since you're unfamiliar with the debugger, just hit F10 once it stops on the breakpoint).

    I notice that it's a WPF window ... I don't think that has anything to do with it, but I haven't done much with WPF. On the off-chance that it *does* matter, if using the debugger doesn't turn up anything enlightening, try taking your calls to FillInstitutionListBox1() and InitializeEmptyChart() out of the constructor and put them in the Loaded event handler and see if that makes a difference (grasping at straws here) ...


    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Wednesday, October 6, 2010 3:37 PM
  • My guess on what's happening?  You're running this in the debugger, right?  So you're getting a 'first-chance' exception, and the code is stopping there, because Visual Studio is configured to immediately stop on First-Chance exceptions.

     

    Try this:  Click on Debug->Exceptions

    In the window that pops up, you should see a list of exception types, and two columns of check-boxes: Thrown and User-Handled.

    I'm guessing that, under the "Common Language Runtime Exceptions", both the Thrown and User Handled check-boxes are checked.

    You can do one of two things: 

    1. Set a breakpoint on your exception handler hit F5 (Continue) when that exception occurs, and your BP should be hit.

    2. Uncheck 'Thrown' in the Exceptions window above.  Note that if you do this, exceptions won't be shown AT ALL if they are caught in a try/catch.  If you're just testing or only hit the condition once or twice, I recommend #1.

     

    Phil

     

    • Proposed as answer by Mike Dos Zhang Monday, October 11, 2010 11:53 AM
    • Marked as answer by Mike Dos Zhang Tuesday, October 12, 2010 11:39 AM
    Wednesday, October 6, 2010 6:09 PM