Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using this video to try and populate results from a DataGridView, and am receiving the above error. The below code pertains to this error - I pass values into a 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();
like image 773
user123 Avatar asked Jun 02 '13 14:06

user123


1 Answers

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

SqlCommand select = new SqlCommand("SELECT * FROM Table", con);
like image 194
John Woo Avatar answered Oct 26 '22 23:10

John Woo