Failure to popular a gridView

Asked

Viewed 74 times

2

I am having problems when displaying a gridView, it is not displaying the right data, it seems that this trying to display vertically, I have already changed the property Gridline to horizontal, Both and now this Name, like another gridView that I have working. This gridView of mine is being populated with information coming from the database. This is my gridView:

     <asp:GridView ID="gridacao" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" ForeColor="#333333" GridLines="None" ToolTip="Valores Atualizados das ações" Width="344px">
         <AlternatingRowStyle BackColor="Gainsboro" />
         <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
         <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
         <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
         <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
         <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
         <SortedAscendingCellStyle BackColor="#F1F1F1" />
         <SortedAscendingHeaderStyle BackColor="#0000A9" />
         <SortedDescendingCellStyle BackColor="#CAC9C9" />
         <SortedDescendingHeaderStyle BackColor="#000065" />
     </asp:GridView>

in part . Cs this so:

public partial class ExibeAcao : System.Web.UI.Page
{
    string cd;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                exibirAcao();

            }
        }
        catch (Exception ce1)
        {

            throw new Exception(ce1.Message.ToString());
        }
    }
    private void exibirAcao()
    {
        try
        {
            cd = "PETR4";
            Trataformes tf = new Trataformes();
            this.gridacao = tf.mostraAcao(cd, ref gridacao);
        }
        catch (Exception e2)
        {

            throw new Exception(e2.Message.ToString());
        }
    }
    protected void gridacao_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

}

The Show() method is this:

public GridView mostraAcao(string cd, ref GridView gv)
    {
        try
        {
            ManipulaBanco mp = new ManipulaBanco();
            return mp.exibeAcao(cd, ref gv);
        }
        catch (Exception e)
        {

            throw new Exception(e.Message.ToString());
        }
    }

and the method removed from the database is this:

 public GridView exibeAcao(string cod, ref GridView tb)
    {
        try
        {
            bancotccEntities bc = new bancotccEntities();
            var pa = from ac in bc.acao
                     where ac.codigo == cod
                     select new
                     {
                         Ação = ac.codigo,
                         Empresa = ac.empresa,
                         Tipo = ac.tipo,
                         Data = ac.data,
                         Hora = ac.hora,
                         Abertura = ac.abertura,
                         Maxima = ac.maxima,
                         Minima = ac.minima,
                         Média = ac.medio,
                         Valor = ac.fechamento,
                         fechamento_Ontem = ac.f_anterior,
                         Volume_de_Ações = ac.volume,
                         Valor_Negociado = ac.v_financeiro,
                         Variação = ac.variacao,
                         Fase = ac.fase
                     };
            tb.DataSource = pa.ToString();
            tb.DataBind();
            return tb;
        }
        catch (Exception e)
        {

            throw new Exception(e.Message.ToString());
        }
    }

am getting the result below: inserir a descrição da imagem aqui

I’d like it to be displayed horizontally, someone knows how?

  • 1

    tb.DataSource = pa.ToString(); It’s wrong here, it wouldn’t be;tb.DataSource = pa.ToList();

  • It is!! Wrong method, only now it is not displaying anything.

  • Breakpoint is the only solution ...

  • 2

    First thing you do is this AutoGenerateColumns="False" place AutoGenerateColumns="True" if carrying was that.!

1 answer

2


Change to the following:

          var pa = from ac in bc.acao
                 where ac.codigo == cod
                 select new
                 {
                     Ação = ac.codigo,
                     Empresa = ac.empresa,
                     Tipo = ac.tipo,
                     Data = ac.data,
                     Hora = ac.hora,
                     Abertura = ac.abertura,
                     Maxima = ac.maxima,
                     Minima = ac.minima,
                     Média = ac.medio,
                     Valor = ac.fechamento,
                     fechamento_Ontem = ac.f_anterior,
                     Volume_de_Ações = ac.volume,
                     Valor_Negociado = ac.v_financeiro,
                     Variação = ac.variacao,
                     Fase = ac.fase
                 };
        tb.DataSource = pa.ToList();
        tb.DataBind();

As the columns did not appear, it may be necessary to implement an automatic column generator for your GridView

1. Declare a class DynamicTemplate

public class DynamicTemplate : System.Web.UI.ITemplate

2. Declare a constructor in which the type of the item is configured

public DynamicTemplate(System.Web.UI.WebControls.ListItemType type)
{
    templateType = type;
}

3. Create a method in your common class that populates Gridview

public void AddControl(WebControl wbControl, 
            String BindPropertyName, String BindExpression)
{
    htControls.Add(htControls.Count, wbControl);
    htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName);
    htBindExpression.Add(htBindExpression.Count, BindExpression);
}

5. Define another method that configures the container

public void InstantiateIn(System.Web.UI.Control container)
{
    PlaceHolder ph = new PlaceHolder();
    for (int i = 0; i < htControls.Count; i++)
    {
        //clone control 
        Control cntrl = CloneControl((Control)htControls[i]);
        switch (templateType)
        {
            case ListItemType.Header:
                break;
            case ListItemType.Item:
                ph.Controls.Add(cntrl);
                break;
            case ListItemType.AlternatingItem:
                ph.Controls.Add(cntrl);
                ph.DataBinding += new EventHandler(Item_DataBinding);
                break;
            case ListItemType.Footer:
                break;
        }
    }
    ph.DataBinding += new EventHandler(Item_DataBinding);
    container.Controls.Add(ph);
}

6. Use as follows

foreach (var propriedade in pa.GetType().GetProperties()) {
    TemplateField t = new TemplateField();
    DynamicTemplate mt = new DynamicTemplate(ListItemType.Item);
    TextBox t1 = new TextBox();
    t1.ID = propriedade.GetName();
    t1.Visible = true;
    t1.Text = propriedade.GetName();
    mt.AddControl(t1, "Text", propriedade.GetName());

    BoundField bf = new BoundField();

    bf.DataField = propriedade.GetName();
    bf.HeaderText = propriedade.GetName();

    tb.Columns.Add(mt);
    tb.Columns.Add(bf);
}

Source: http://www.codeproject.com/Articles/17078/Dynamically-Adding-Template-Columns-to-a-GridView

  • I changed the thin code from Tostring() to Tolist(), but now nothing is appearing.

  • @user9090 Possibly you have to add the columns dynamically. I modified my answer.

  • 1

    I got it! Good thing I didn’t have to add the columns dynamically, it was, just change the property cited by Harry. Thanks for the personal help. To tell you the truth I have to read more about how to generate columns dynamically, because you never know when you will need.

Browser other questions tagged

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