LearnFast.Ninja

Get DataSet from SQL Server C Sharp ASP.NET

This function get connection string from web config. Then we create instance of SqlConnection object. We building try and catch block but only with try and finally, we want to make sure the connection always be close. This function return DataSet and fill it using adapter. Note if the connection is close before Fill was call it is opened to retrieve data and then closed. If the connection is open before Fill is called then it will remain open.

Working function example:

public static DataSet GetDataSetNoParameters(string Query)

{

    string myConnectionString = ConfigurationManager.ConnectionStrings["Connection_Name"].ConnectionString;

    SqlConnection oSqlConnection = new SqlConnection(myConnectionString);

    try

    {

        SqlCommand cmd = new SqlCommand(Query, oSqlConnection);

        SqlDataAdapter oSqlDataAdapter = new SqlDataAdapter(cmd);

        DataSet DataSet_To_Fill = new DataSet();

        oSqlDataAdapter.Fill(DataSet_To_Fill);

        return DataSet_To_Fill;

    }

    finally

    {

        oSqlConnection.Close();

    }

}// end function


Tags

asp.net

dal dataaccess dataset adapter sqldataadapter sqlcommand sqlconnection