troubleshooting Question

Combine { using } statement and {try-catch} statement in C#

Avatar of niceguy971
niceguy971 asked on
C#.NET ProgrammingASP.NET
8 Comments5 Solutions1885 ViewsLast Modified:
What would be the best way to combine  {try-catch} statement and { using } statement?

Just put { using } statement in try section??

    try 
    {
       // Put using statement here
       
    }
    catch (Exception ex) 
    {
       // handle exception
    }

The below code (I got it from http://www.aspsnippets.com/Articles/Export-data-from-SQL-Server-to-Text-file-in-C-and-VBNet.aspx)  does Not handle Exceptions. What would be the best way to fix it??

Put block { using (SqlConnection con = new SqlConnection(constr)) }  in try section??

    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
 
                    //Build the Text file data.
                    string txt = string.Empty;
 
                    foreach (DataColumn column in dt.Columns)
                    {
                        //Add the Header row for Text file.
                        txt += column.ColumnName + "\t\t";
                    }
 
                    //Add new line.
                    txt += "\r\n";
 
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            //Add the Data rows.
                            txt += row[column.ColumnName].ToString() + "\t\t";
                        }
 
                        //Add new line.
                        txt += "\r\n";
                    }
                }
            }
        }
    }

Thanks
SOLUTION
AndyAinscow
Freelance programmer / Consultant

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 5 Answers and 8 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 5 Answers and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros