My Default Helper Class

09 Mar

Just wanted to post what I have as my default helper class it is small just 2 methods but I use it in almost every project I do. the first one gets your connection string and the other executes a sql sommand that returns a table.

just fill in the catchs with your own error logging/handeling if you wish to do it or just leave it be and return null( I don’t recommend this but you can) and well there you go. use your helper class for any common code snippet you use over and over instead of writing the same thing all the time.

public class Helpers
        /// <summary>
        /// Returns the current connection string
        /// </summary>
        /// <returns></returns>
        public SqlConnection getConnection()
            SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
            return Con;

        /// <summary>
        /// Returns a DataTable, based on the command passed
        /// </summary>
        /// <param name="cmd">
        /// the SqlCommand object we wish to execute
        /// </param>
        /// <returns>
        /// a DataTable populated with the data 
        /// specified in the SqlCommand object
        /// </returns>
        /// <remarks></remarks>
        public DataTable GetDataTable(SqlCommand cmd)
                // create a new data adapter based on the specified query.
                using (SqlDataAdapter da = new SqlDataAdapter() { SelectCommand = cmd })
                    // create a new DataTable
                    DataTable dtGet = new DataTable();
                    //fill the DataTable
                    //return the DataTable
                    return dtGet;
            catch (SqlException ex)
                return null;
            catch (Exception ex)
                return null;

Leave a comment

Posted by on March 9, 2012 in C#, C# for Beginners


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: