Enzo
Enzo

Reputation: 1

Connection must be valid and open error in visual studio

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 :)

Upvotes: 0

Views: 1082

Answers (3)

GarethD
GarethD

Reputation: 69789

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

Upvotes: 1

Dream Land
Dream Land

Reputation: 41

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);

Upvotes: 0

mankerufer
mankerufer

Reputation: 1

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

Upvotes: 0

Related Questions