-2

I am getting error:

Connection must be valid and Open c# Winform.

Here is my code, can anyone please help what is wrong in the below code?

public void NameSearch()
    {
        listBox1.Visible = true;

        try
        {
        String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
        string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";

        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
        MySqlDataReader myReader = cmdDataBase.ExecuteReader();

        while (myReader.Read())
        {
        string Lname = myReader.GetString(myReader.GetOrdinal("StudLname"));
        string Fname = myReader.GetString(myReader.GetOrdinal("StudFname"));
        string Mname = myReader.GetString(myReader.GetOrdinal("StudMname"));
        string nameResult = Lname + ", " + Fname + "  " + Mname;
        listBox1.Items.Add(nameResult);
        }
        conDataBase.Close();
    }
    catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
  • 1
    conDataBase.Open() – Sarvesh Mishra Aug 31 '16 at 07:26
  • Possible duplicate of [Connection must be valid and open error](http://stackoverflow.com/questions/4233185/connection-must-be-valid-and-open-error) – Sayse Aug 31 '16 at 07:31
  • MySqlConnection conDataBase = new MySqlConnection(constring); MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase); MySqlDataReader myReader = cmdDataBase.ExecuteReader(); conDataBase.Open(); Same error. – Eugene Ganancial Aug 31 '16 at 07:36

2 Answers2

1

You haven't open connection before use it, Open connection

conDataBase.Open();
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
0

Open the conn before read:

conDataBase.Open();

Like:

    String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
    string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";

    MySqlConnection conDataBase = new MySqlConnection(constring);
    MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
    //
    conDataBase.Open();
    //
    MySqlDataReader myReader = cmdDataBase.ExecuteReader();
S. Medina
  • 76
  • 1
  • 8