Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C“错误:”;填充:SelectCommand。连接属性尚未初始化;_C#_Sql Server_Datagridview - Fatal编程技术网

C# C“错误:”;填充:SelectCommand。连接属性尚未初始化;

C# C“错误:”;填充:SelectCommand。连接属性尚未初始化;,c#,sql-server,datagridview,C#,Sql Server,Datagridview,我正在使用尝试从一个DataGridView填充结果,并收到上述错误。下面的代码与此错误有关-我将值传递到存储过程中,然后最后的SELECT返回DataGridView中表中的值 SqlConnection con = new SqlConnection(); con.ConnectionString = "integrated security=SSPI;data source=SERV;" + "persist security info=False;init

我正在使用尝试从一个
DataGridView
填充结果,并收到上述错误。下面的代码与此错误有关-我将值传递到存储过程中,然后最后的
SELECT
返回
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();

您没有在
命令上传递
连接
对象。试试这个

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

您正在将连接对象传递给enter命令,但未将连接对象传递给select命令

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

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

谢谢你的目光抓住了我的错误。@JohnWoo:这也帮了我的忙+1:)它会给你带来什么错误?虽然这段代码可能会回答这个问题,但提供关于它如何和/或为什么解决问题的附加上下文将提高答案的长期价值。
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2") // connection missing in sqlcommand

SqlCommand cmd = new SqlCommand("sp_StockAnalysis2",Connection())// pass connection