Home > Mobile >  Connection must be valid and open error in visual studio
Connection must be valid and open error in visual studio

Time:02-25

I'm trying to show in my datagridview all the registers from a mariadb database, but when I start the code, it appears the errror "Connection must be valid and open error", the code is Here:

I'll be glad if somebody can help me :)

CodePudding user response:

Delete MysqlCommand cmd = new MySqlCommand("") row and try it

        using (var sqlCommand = new MySqlCommand("SELECT * FROM encomendas", bdcon))
        {
            MySqlDataReader read = sqlCommand.ExecuteReader();
            dt.Load(read);

        }

try it

CodePudding user response:

Your object of MysqlCommand must have association with your object MysqlConnection. Obviously your cmd has no business with bdcon, that is the reason why it says "Connection must be valid and open error" when you call the method ```cmd.ExecuteNonQuery(). Here is a similar snippet.

SqlConnection sqlConnection = new SqlConnection();
SqlCommand cmd = sqlConnection.CreateCommand();
//or
SqlCommand cmd = new SqlCommand("sql text", sqlConnection);

CodePudding user response:

There are two main problems with your code. Firstly you don't associate your connection object with your command object, instead of

MySqlCommand cmd = new MySqlCommand("SELECT * FROM encomendas");

It should be

MySqlCommand cmd = new MySqlCommand("SELECT * FROM encomendas", bdcon);

Also, there is no need to call cmd.ExecuteNonQuery(). It is also advisable to use using blocks on objects that implement IDisposable to ensure they are disposed of correctly, so your full code might be:

var datatable = new DataTable();
using (var connection = new MySqlConnection("connectionstring"))
using (var command = new MySqlCommand("SELECT * FROM encomendas", connection ))
{
    connection.Open()'
    using (var reader = command.ExecuteReader())
    {
         datatable.Load(reader);
    }
}
// Bind to your grid view

With that being said, if you are looking to fill a DataTable then MySqlDataAdapater() is the simplest approach:

var dt = new DataTable();
using (var adapter = new MySqlDataAdapter("SELECT * FROM encomendas", "ConnectionString"))
{
    adapter.Fill(dt);
}
// Bind to your grid view
  • Related