Gridiview in Asp.net mounting

Asked

Viewed 43 times

0

Good afternoon, you guys. I have a doubt when it comes time to mount a gridview I do not possess much knowledge in c# I did so

 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 there is more than one return line when it has only one it assembles nothing and shows nothing someone has an idea of how to do?

thank you

1 answer

0


You don’t need to iterate on the DataReader to do the DataBind. Just define the DataSource and call the 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));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.