What is needed to open a connection and close query execution in winform?

There are a lot of combo boxes in my form. I want to load different table data in a combo box. I am trying to do this, but the code is very slow due to the connection between open and closed encodings.

When I run two commands without a close connection and open it, it throws an exception.

There is already an open DataReader associated with this connection, which should be closed first.

How can I remove this opening and close in my program? Here is my code:

string MyConString = ConfigurationManager.ConnectionStrings["College_Management_System.Properties.Settings.cmsConnectionString"].ConnectionString;
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select name from course_master";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
    cmbo_course.Items.Add(Reader[0].ToString());
}

command.CommandText = "select name from country_master";
Reader = command.ExecuteReader();
while (Reader.Read())
{
    cmbo_perCountry.Items.Add(Reader[0].ToString());
    cmbo_country.Items.Add(Reader[0].ToString());
}
connection.Close();
+5
source share
1 answer

Try using

Reader = command.ExecuteReader ( CommandBehavior.CloseConnection () );
+3

All Articles