1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

it gives an error "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."
@Dany In your question you say the table name is HUGGO_BOSS, but in the SQL code you're querying table HUGO_BOSS (only one G). Are you sure the SQL query is correct? Also, what type is comboBox3.SelectedItem?
sorry, actually there is a typing mistake in question.The correct spelling is HUGO_BOSS and my combobox3 contains the list of brand name from the database. If a users selects a particular brand name, then my textbox should give its quantity available in the stock.
@Dany If SelectedItem is a string, are you sure that [Brand Name] in a varchar or nvarchar (or char / nchar)? Also, did you specify the database name in your connection string?
yes i specified the database name in connection string. and my brand name is a text. Actually i am using ms access database.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.