C# C语言,access作为数据库。如果选择组合框,则文本框中的数据库值
我有一个错误,显示连接未关闭。 我甚至试着把一个最后,但它没有工作C# C语言,access作为数据库。如果选择组合框,则文本框中的数据库值,c#,database,ms-access,C#,Database,Ms Access,我有一个错误,显示连接未关闭。 我甚至试着把一个最后,但它没有工作 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { try { connection.Open(); OleDbCommand command = new OleDbCommand(); command.Connection = connection;
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);
}
不要进行连接。手动关闭,在“使用”块中创建连接: usingvar connection=新建SqlConnection。。。 { OleDbCommand命令=新的OleDbCommand; ........ }
这样,您就不必担心关闭连接。一旦using块结束,连接也会结束。请将问题中的代码以文本形式发布。图像很难读取,也无法创建代码来测试您的问题,如果您在OleDbConnection类型的全局变量上出现连接打开错误,则需要检查忘记关闭该连接的代码的每个部分,例如,如果您输入了一个catch块,忘记关闭启动程序的连接,您应该始终在finally block中关闭连接。是否可能是第一次出现异常导致了连接。close将被跳过,而我们在屏幕截图中看到的异常是第二次出现的?您是否有其他代码打开连接。这在这里也很重要。