Reputation:
I have a database in which I created a table HUGO_BOSS
. Its columns are [brand name]
, [stock quantity]
, [retail price]
and its primery key is [Brand name]
. I want to fill my textbox in windows form with the value of stock quantity present in my database. I tried the following code but it gives run-time error
The Connection was not close, the connection state is open.
if (comboBox2.Text == "HUGO BOSS")
{
try
{
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "Select [Stock quantity] as stockquantity from HUGO_BOSS WHERE [Brand name]=@name";
cmd.Parameters.AddWithValue("@name", comboBox3.SelectedItem);
con.Open();
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
textBox7.Text = dr["stockquantity"].ToString();
}
}
finally { con.Close(); }
}
One more thing, here I will select the primary key by using a combobox3
Upvotes: 1
Views: 7674
Reputation: 148980
It looks you're trying to reuse a database connection that is already open.
You could try testing the connection state before trying to open it:
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "Select [Stock quantity] as stockquantity from HUGO_BOSS WHERE [Brand name]=@name";
cmd.Parameters.AddWithValue("@name", comboBox3.SelectedItem);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
textBox7.Text = dr["stockquantity"].ToString();
}
Alternatively, you could create a new connection each time you need to execute a new command.
Upvotes: 1