C# 错误:“填充:SelectCommand.Connection 属性尚未初始化。”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16883654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Error: "Fill: SelectCommand.Connection property has not been initialized."
提问by user123
I'm using this videoto 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 SELECTreturns the values in the table in the DataGridView.
我正在使用此视频尝试从 a 填充结果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();
采纳答案by John Woo
You did not pass connectionobject on the command. Try this instead,
您没有connection在command. 试试这个,
SqlCommand select = new SqlCommand("SELECT * FROM Table", con);
回答by Kurubaran
You are passing connection object to your entercommand but didnt pass the connection object to your selectcommand
您正在将连接对象传递给您的输入命令,但没有将连接对象传递给您的选择命令
SqlCommand select = new SqlCommand("SELECT * FROM Table");
SqlCommand enter = new SqlCommand("sp_Proc", con);
Use this
用这个
SqlCommand select = new SqlCommand("SELECT * FROM Table",con);
回答by Aman singh
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2") // connection missing in sqlcommand
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2",Connection())// pass connection

