Reputation: 47
My code is like this : I input the caseid in the textbox and try to click Find button to find the corresponding result. But Visual studio always says :error occored The connection was not closed The connection current state is open.
This is my first time design ADO.NET myself and I need to finish my advisor research tasks.
Could you check the code and tell me what wrong?
Thanks Sophia
using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace casestudy
{
public partial class Form1 : Form
{
SqlConnection vcon1 = new SqlConnection(@"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
vcon1.Open();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
private void Find_Click(object sender, EventArgs e)
{
string querystring = "SELECT * FROM AssignedSolution WHERE CASEID = @caseid";
SqlCommand Vcom = new SqlCommand(querystring, vcon1);
Vcom.Parameters.AddWithValue("@caseid", txtCASEID);
SqlDataReader rdr = null;
try
{
Vcom.Connection = vcon1;
vcon1.Open();
Vcom.ExecuteNonQuery();
//DataSet vds1 = new DataSet();
rdr = Vcom.ExecuteReader();
//vDa1.Fill(vds1, "res");
//dataGridView1.DataSource = vds1.Tables["res"];
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
Vcom.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
}
finally
{
vcon1.Close();
vcon1.Dispose();
}
}
Upvotes: 0
Views: 54
Reputation: 11514
The connection is being opened on Form1_Load
event, then you are trying to open the same connection again in the Find_Click
event. You can't open a connection that is already open. Just remove all code from the load event, you don't need it.
Upvotes: 1