2016-05-30 60 views
-1

image 1 我有一個錯誤,顯示連接未關閉。
我甚至通過把一個最後但還沒試過它不工作。數據庫值在文本框中,如果選擇Combobox

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    try 
    { 

     connection.Open(); 
     OleDbCommand command = new OleDbCommand(); 
     command.Connection = connection; 
     string query = "SELECT * FROM Dataaa WHERE FirstName='" + comboBox1.Text + "'"; 
     command.CommandText = query; 
     OleDbDataReader reader = command.ExecuteReader(); 
     while (reader.Read()) 
     { 
      txt_EID.Text = reader["EID"].ToString(); 
      textBox1.Text = reader["Firstname"].ToString(); 
      textBox2.Text = reader["LastName"].ToString(); 
      textBox3.Text = reader["ICNO"].ToString(); 
      textBox4.Text = reader["Address"].ToString(); 
      textBox5.Text = reader["Loan"].ToString(); 
      textBox6.Text = reader["Percent"].ToString(); 
      textBox7.Text = reader["Payback"].ToString(); 
      textBox8.Text = reader["StartDate"].ToString(); 
      textBox9.Text = reader["EndDate"].ToString(); 
      textBox10.Text = reader["Monthly"].ToString(); 
      textBox11.Text = reader["PaymentType"].ToString(); 
      textBox12.Text = reader["Remark"].ToString(); 

     } 
     connection.Close(); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show("error " + ex); 
    } 
+0

請將您的問題中的代碼發佈爲TEXT。圖像難以閱讀,也無法創建代碼來測試您的問題 – Steve

+0

如果您在OleDbConnection類型的全局變量上發生連接打開錯誤,則需要檢查代碼中忘記關閉該連接的每個部分(例如如果你輸入一個catch塊並忘記關閉連接) – Steve

+0

對於初學者,你應該總是關閉你的連接在finally塊中。 –

回答

1

代替人工手動操作的Connection.close的,建立在「使用」塊的連接:

using(var connection = new SqlConnection(...)) { OleDbCommand command = new OleDbCommand(); ........ }

這你不需要擔心關閉連接。一旦使用塊結束,連接也一樣。

相關問題