C # Error: "Fill: The SelectCommand.Connection property has not been initialized."

I use this video to try to populate the results from a DataGridView and I get the above error. The code below refers to this error: I pass the values ​​to the stored procedure, then the final SELECT returns the values ​​in the table in the DataGridView .

  SqlConnection con = new SqlConnection(); con.ConnectionString = "integrated security=SSPI;data source=SERV;" + "persist security info=False;initial catalog=DB"; con.Open(); SqlCommand select = new SqlCommand("SELECT * FROM Table"); SqlCommand enter = new SqlCommand("sp_Proc", con); // Stored Procedure enter.CommandType = CommandType.StoredProcedure; enter.Parameters.Add(new SqlParameter("@vvalue", SqlDbType.VarChar)).Value = Convert.ToString(txt1.Text); enter.Parameters.Add(new SqlParameter("@dvalue", SqlDbType.Decimal)).Value = Convert.ToDecimal(txt2.Text); enter.ExecuteNonQuery(); // DataGrid returns the SELECT SqlDataAdapter sadapt = new SqlDataAdapter(select); sadapt.SelectCommand = select; DataTable dtab = new DataTable(); sadapt.Fill(dtab); // generates the error BindingSource b = new BindingSource(); b.DataSource = dtab; dGrid.DataSource = b; sadapt.Update(dtab); con.Close(); 
+7
source share
2 answers

You did not pass the connection object to command . Try this instead

 SqlCommand select = new SqlCommand("SELECT * FROM Table", con); 
+13
source

You pass the connection object to your command type , but did not pass the connection object to the select command

  SqlCommand select = new SqlCommand("SELECT * FROM Table"); SqlCommand enter = new SqlCommand("sp_Proc", con); 

Use this

 SqlCommand select = new SqlCommand("SELECT * FROM Table",con); 
+1
source

All Articles