2013-06-02 242 views
7

我正在使用this video嘗試填充DataGridView的結果,並且正在接收上述錯誤。以下代碼與此錯誤有關 - 我將值傳遞給存儲過程,然後最後的SELECT返回DataGridView表中的值。C#錯誤:「填充:SelectCommand.Connection屬性尚未初始化。」

 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(); 
+0

它給你什麼錯誤? –

回答

13

你沒有在command通過connection對象。試試這個,

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

謝謝;你的眼睛引起了我的錯誤。 – user123

+0

不客氣':)' –

+0

@JohnWoo:它也幫助了我.. +1 :) – BNN

1

你傳入連接對象的進入命令但沒有通過連接對象的選擇命令

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

使用此

SqlCommand select = new SqlCommand("SELECT * FROM Table",con); 
相關問題