Dc2b5374b8c24a20577346b9b1e4891f

i try to write a winform application:
i dislike below codes:
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);

<b>Above part of codes looks unsufficient.How can i best loading dataset?</b>

public class LoadDataset
    {
        public DataSet GetAllData(string sp)
        {
            return LoadSQL(sp);
        }
        private DataSet LoadSQL(string sp)
        {
            SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand(sp, con);
            DataSet ds;
            try
            {
                con.Open();

                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                ds = new DataSet();
                ds.Tables.Add(dt);
                return ds;
            }
            finally
            {
                con.Dispose();
                cmd.Dispose();
            }
        }
    }

Refactorings

No refactoring yet !

F9a9ba6663645458aa8630157ed5e71e

Ants

June 3, 2010, June 03, 2010 00:36, permalink

No rating. Login to rate!

Take advantage of the 'using' keyword. Check out the sample code under the docs for SqlDataReader:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

For your code, just replace the sample's while loop, with your DataTable creation and Load() call.

94f928c5cde29a190e2062fc7bb7fbdb

Kathy Wu

June 3, 2010, June 03, 2010 02:32, permalink

1 rating. Login to rate!
public class LoadDataset
    {
        public static DataSet Load(string sp)
        {
            DataSet ds = new DataSet();

            using (SqlConnection conn = CreateConnection())
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(sp, conn);
                da.Fill(ds, "myDataSet");
            }

            return ds;
        }

        private static SqlConnection CreateConnection()
        {
            return new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
        }
    }

Your refactoring





Format Copy from initial code

or Cancel