Error including sum of values in the footer of a gridview

Asked

Viewed 888 times

1

I’m trying to include in the footnote of a gridview the sum of two columns, but I’m having difficulty creating the method that performs this function.

I’ve already put the property ShowFooter as true, now I have to implement the event DataBound but it’s not working. Someone can help me?

 protected void gvcarteira_DataBound(object sender, EventArgs e)
    {
                    double val1 = 0;
        double val2 = 0;
       // foreach (GridViewRow row in gvcarteira.Rows)

        for (int i; gvcarteira.Rows.Count - 1; i++)
        {
            // converte o preco e a qtde para multiplicar e somar no total         

            double qt = double.Parse(gvcarteira.Rows[i].Cells[3].Text);
            double qtd = double.Parse(gvcarteira.Rows[i].Cells[4].Text);


            val1 = val1 + qt;
            val2 = val2 + qtd;


        }
        gvcarteira.FooterRow.Cells[0].Text = "Valor das Ações";
        gvcarteira.FooterRow.Cells[1].Text = val1.ToString();

        gvcarteira.FooterRow.Cells[3].Text = "Valor Gasto";
        gvcarteira.FooterRow.Cells[4].Text = val2.ToString();
      }

I want it to look something like this: inserir a descrição da imagem aqui

  • The way to define values is correct. What exactly is happening with the GridView?

  • (gvcarteira. Rows[i]. Cells[3]. Text), as in this case the i of the error was not declared, but I leave the error.

  • The mistake then happens here: double qt = double.Parse(gvcarteira.Rows[i].Cells[3].Text);

  • It is one of the cases depending on the type of loop I implement, if it is the foreach the error is in i that has not been stated. if use is the error in gvcarteira.Rows.Count - 1 .

  • But it has been declared. I will put an answer to you.

2 answers

1


Example:

Gridview:

<asp:GridView ID="GridDados" AutoGenerateColumns="False" runat="server" ItemType="WebAppDiegoWebForms.Fulano" OnRowDataBound="GridDados_RowDataBound" ShowFooter="True">
    <Columns>
        <asp:BoundField DataField="Codigo" HeaderText="Código" DataFormatString="{0:0000}"/>
        <asp:BoundField DataField="Nome" HeaderText="Nome" />
        <asp:BoundField DataField="Data" DataFormatString="{0:d}" HeaderText="Data" />
        <asp:BoundField DataField="Quantidade" HeaderText="Quantidade" />
        <asp:BoundField DataField="Valor" DataFormatString="{0:N2}" HeaderText="Valor" />
        <asp:BoundField DataField="ValorParcial" DataFormatString="{0:N2}" HeaderText="Valor Parcial" />
    </Columns>
</asp:GridView>

In his Griddados has the columns Amount, Valor and Partial value and in the Footer will be summing all values of Partial value.

Like:

Class model:

public class Fulano
{
    public int Codigo { get; set; }
    public string Nome { get; set; }
    public DateTime Data { get; set; }
    public Decimal Valor { get; set; }
    public int Quantidade { get; set; }
}

Code of this Webform

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var valores = (new Fulano[] 
        {
            new Fulano { Codigo = 1,  Nome = "Fulano 1", Data = DateTime.Now, Valor = 100M, Quantidade = 2},
            new Fulano { Codigo = 2, Nome = "Fulano 2", Data = DateTime.Now, Valor = 200M, Quantidade = 1},
            new Fulano { Codigo = 3, Nome = "Fulano 3", Data = DateTime.Now, Valor = 100M, Quantidade = 1},
            new Fulano { Codigo = 4, Nome = "Fulano 4", Data = DateTime.Now, Valor = 150M, Quantidade = 1},
            new Fulano { Codigo = 5, Nome = "Fulano 5", Data = DateTime.Now, Valor = 300M, Quantidade = 1}
        })
        .Select(x => new
        {
            x.Codigo,
            x.Nome,
            x.Data,
            x.Valor,
            x.Quantidade,
            ValorParcial = (x.Valor * x.Quantidade)
        })
        .ToArray();

        GridDados.DataSource = valores;
        GridDados.DataBind();
    }
}

private decimal total = 0;
private decimal valor = 0;        
protected void GridDados_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        valor = 0;               
        if (decimal.TryParse(e.Row.Cells[5].Text, out valor)){
            total += valor;
        }

    } else if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[4].Text = "Total:";
        e.Row.Cells[5].Text = total.ToString("N2");
        total = 0;
    }            
}

Loading in this example is manual, but you can use it in your own way. The only pecularity that before sending to GridView Griddados I do a multiplication ValorParcial = (x.Valor * x.Quantidade) and send the data to grid all formatted.

In the GridDados_RowDataBound i do the proper sum operations and at the end I show in the Footer of Gridview. OBS: the variables of type decimal total and value are placed outside the method GridDados_RowDataBound.

Upshot:

inserir a descrição da imagem aqui

0

The problem is not the footer itself. It is the loop iteration. Consider changing the for by a foreach, which is safer:

foreach (GridViewRow linha in gvcarteira.Rows)
{
    // converte o preco e a qtde para multiplicar e somar no total         

    double qt = double.Parse(linha.Cells[3].Text);
    double qtd = double.Parse(linha.Cells[4].Text);

    val1 = val1 + qt;
    val2 = val2 + qtd;

}
  • The visual studio is not recognizing Cells, this giving me the error below: 'Object' does not contain a Definition for 'Cells' and no Extension method 'Cells' Accepting a first argument of type 'Object' could be found (are you Missing a using Directive or an Assembly Reference?)

  • Ah, yes. Pardon. I edited. Look now.

  • have to add some using?

  • using System.Data, if there is no.

  • With this using it does not recognize Cells, without it vs does not recognize Datarow. would not be Row.Cells?

  • Right. I modified it again.

  • ok now a compilation error appears: Undefined object reference to an instance of an object. it would not be because I pass the data by reference to the gridview?

  • I don’t know. Just checking by breakpoint now.

  • only one more question this code goes on which event ? in Databound or Rowdatabound?

  • The ideal would be to RowDataBound, and you go setting the total to each line.

  • The total of each row I already have is trying to define the overall total of a specific column.

  • No, no. I said, the total each line, no of each line.

Show 7 more comments

Browser other questions tagged

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