I am programming in Windows Forms and MySQL.
If I declare this in the program, I can use the connection and command objects in the whole .cs page:
MySqlConnection connection = null;
MySqlCommand command = null;
MySqlDataReader Reader;
But if I write the code below, connection and command objects are declared twice:
private void cmbo_class_SelectedValueChanged(object sender, EventArgs e)
{
string clas = cmbo_class.SelectedItem.ToString();
try
{
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select id,code from reg_class_master where name ='" + clas + "' and Delete_Status=0";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
class_id = Convert.ToInt32(Reader[0].ToString());
class_code = Reader[1].ToString();
}
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error in ","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
cmbo_division.Items.Clear();
try
{
MySqlConnection connection = new MySqlConnection(hp.myConnStr);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select name from reg_division_master where class_id = " + class_id + " and Delete_Status=0 order by display_index";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
cmbo_division.Items.Add(Reader[0].ToString());
}
connection.Close();
}
catch
{
}
I think one object declaration is the best way. Do more object declarations affect the program?