2017-07-11 134 views
1

我得到錯誤「System.Runtime.InteropServices.InvalidComObjectException:'已從其基礎RCW分離的COM對象不能使用。只有當我在using塊執行OleDbCommand對象與parametersOleDbCommand在使用塊:已經從其基礎RCW分離的COM對象不能使用

using (OleDbCommand comm = new OleDbCommand()) 
     { 
      comm.Connection = conn; 
      comm.CommandType = CommandType.Text; 
      string txt = "SELECT* FROM [ListForGroup] WHERE [email] = @email"; 
      comm.Parameters.Add("@email", OleDbType.VarWChar).Value = userEmail; 
      comm.CommandText = txt; 
      conn.Open(); 
      OleDbDataReader reader = comm.ExecuteReader(); 
      List<ListForGroups> list = returnLists(reader); 
      conn.Close(); 
      cmbSelectList.DataSource = list; 
      cmbSelectList.DisplayMember = "listName"; 
      cmbSelectList.ValueMember = "listForGroupsID"; 
     } 

有誰知道原因是什麼。我可以解決它使用OleDbCommand對象與CommandText沒有parameters但我讀這是個壞主意。我想在using區塊中做到這一點,以確保所有資源都將被釋放。

回答

0

我解決了這個問題

using (OleDbConnection conn = new OleDbConnection(connString)) 
    { 
     OleDbCommand comm = new OleDbCommand(); 
     comm.Connection = conn; 
     comm.CommandType = CommandType.Text; 
     string txt = "SELECT* FROM [ListForGroup] WHERE [email] = @email"; 
     comm.Parameters.Add("@email", OleDbType.VarWChar).Value = userEmail; 
     comm.CommandText = txt; 
     conn.Open(); 
     OleDbDataReader reader = comm.ExecuteReader(); 
     List<ListForGroups> list = returnLists(reader); 

     cmbSelectList.DataSource = list; 
     cmbSelectList.DisplayMember = "listName"; 
     cmbSelectList.ValueMember = "listForGroupsID"; 
    } 

我不知道爲什麼我沒有在括號創建OleDbConnection旁邊using。另一種解決方法是在using區塊後關閉connection

相關問題