Avatar of niceguy971
niceguy971

asked on 

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

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
    }

Open in new window


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";
                    }
                }
            }
        }
    }

Open in new window


Thanks
C#.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
niceguy971

8/22/2022 - Mon