System.InvalidOperationException: 'ADP_ConnectionRequired_Fill', Exception Unhandled

1.8k Views Asked by At

i was writing a code in c# for 3 tier approach using CRUD operations in windows based GUI. When i tried to run the code, i got Exception user-unhandled error in the line of code below.

sda.Fill(dt);

you can check the rest of the code below. Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.Configuration;

namespace _3_tierProject1
{
    class DLL
    {
        string constring = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
        //string constring = "Data Source = DESKTOP-A8CA8NG\\SQLEXPRESS ; initial catalog = employeedb ; Integrated Security = SSPI;"

        public DataTable selectDAL()
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand("Select * from emptable"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        sda.Fill(dt);
                        //return dt;
                    }
                }
            }
            return dt;
        }
1

There are 1 best solutions below

0
Erica Yao On BEST ANSWER

Please refer this: ADP_ConnectionRequired_Fill Your SqlCommand does not associate with the SqlConnection.

may you try this:

public DataTable selectDAL()
{
    DataTable dt = new DataTable();
    using (SqlConnection conn = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("Select * from emptable"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;  // <<< add this
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                sda.Fill(dt);
                //return dt;
            }
        }
    }
    return dt;
}