C#错误:“填充:SelectCommand.Connection属性尚未初始化。”

时间:2013-06-02 14:24:21

标签: c# sql-server datagridview

我正在使用this video尝试填充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();

3 个答案:

答案 0 :(得分:14)

您未在connection上传递command个对象。试试这个,

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

答案 1 :(得分:1)

您正在将连接对象传递给输入命令但未将连接对象传递给选择命令

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

使用此

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

答案 2 :(得分:-2)

SqlCommand cmd = new SqlCommand("sp_StockAnalysis2") // connection missing in sqlcommand

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