Gridiview in asp.net assembly

0

Good afternoon, folks. I have a question when setting up a gridview I do not have a lot of knowledge in C # I did it that way

 string sql = "SELECT pr.codigo_chave,pr.codigo_produto,pr.nome_produto,ca.nome_categoria FROM infobook_net.produtos pr inner join categorias ca on pr.codigo_categoria = ca.codigo_categoria";
    Response.Write(sql);

    cmd.CommandText = sql;
    cmd.Connection = sqlConnection1;
    try
    {
        sqlConnection1.Open();
        MySqlDataReader reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                GridView1.DataSource = reader;
                GridView1.DataBind();
            }
        }
        else
        {
            Response.Write("não foram encontrados dados");
        }
    }
    catch (Exception ex)
    {
        Response.Write(Convert.ToString(ex));
    }

It is running and filling the gridview only when it has more than one return line when only one has it it does not mount anything and does not show anything does anyone have an idea how to do it?

Thank you

    
asked by anonymous 25.01.2016 / 17:10

1 answer

0

You do not have to iterate over DataReader to do DataBind. Just set DataSource and call method DataBind as below:

String sql = "SELECT pr.codigo_chave,pr.codigo_produto,pr.nome_produto,ca.nome_categoria FROM infobook_net.produtos pr inner join categorias ca on pr.codigo_categoria = ca.codigo_categoria";
Response.Write(sql);

cmd.CommandText = sql;
cmd.Connection = sqlConnection1;
Try
{
    sqlConnection1.Open();
    MySqlDataReader reader = cmd.ExecuteReader();

    If (reader.HasRows)
    {
        GridView1.DataSource = reader;
        GridView1.DataBind();
    }
    Else
    {
        Response.Write("não foram encontrados dados");
    }
}
Catch (Exception ex)
{
    Response.Write(Convert.ToString(ex));
}
    
25.01.2016 / 20:34