Load DataGridView with MySql

1

I have the following problem to display the data in a gridView pulling from the MySQL database

public string CarregarAluno()
    {
        string retorno = "";

            string sql = "select * from alunos";

            MySqlConnection conn = CriarConexao();
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);

            DataTable data = new DataTable();
            adapter.Fill(data);

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
            retorno = "";

        }
        catch (MySqlException ex)
        { retorno = "Erro ao Carregar Grid: " + ex.Message; }

        finally { if (conn.State == ConnectionState.Open) conn.Close(); }

        return data;
    }

The "return data;" is underlined with the following message: "Can not implicitly convert type System.Data.Data.Table to String"

    
asked by anonymous 29.11.2017 / 12:05

3 answers

1

The signature of the CarregarAluno method is returning a string and at some point you try to return a DataTable . This is your primary compile issue.

To resolve, change the signature of your method to public DataTable CarregarAluno() .

And the method body for

string sql = "select * from alunos";

MySqlConnection conn = CriarConexao();
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);

DataTable data = new DataTable();
adapter.Fill(data);

try
{
   conn.Open();
   cmd.ExecuteNonQuery();
   conn.Close();
   return data;
}
catch (MySqlException ex)
{ 
   throw new Exception($"Erro ao Carregar Grid: {ex.Message}"); 
}
finally 
{
   if (conn.State == ConnectionState.Open) conn.Close(); 
}
return null;
    
29.11.2017 / 12:44
1

You do not need the MySqlDataAdapter

29.11.2017 / 12:50
1

John Víctor,

problem is in method type

  

public DataTable LoadAlumn ()

Change to

public DataTable CarregarAluno()
{
    string retorno = "";

    string sql = "select * from alunos";

    MySqlConnection conn = CriarConexao();
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);

    DataTable data = new DataTable();
    adapter.Fill(data);

    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
        retorno = "";
        return data;
    }
    catch (MySqlException ex)
    { 
        retorno = "Erro ao Carregar Grid: " + ex.Message; 
    }

    finally 
    {
        if (conn.State == ConnectionState.Open) conn.Close(); 
    }
}
    
29.11.2017 / 12:11