How to perform sum per line on a datagridview in c#

Asked

Viewed 616 times

1

Good afternoon, I need a help, I have a datagridview that contains a Type Coin column and a Total Currency column. In the Currency Type column I can have up to 3 types of currency, euro currency, dollar currency and real currency. Now I need to do a sum per currency. Ex sum everything that is euro currency and show in txtboxEuro, then sum everything that is dollar currency and show in textboxDolar. How can I do this

follows the screen of the datagridview. inserir a descrição da imagem aqui

follows my code.

private void ListaGrid()
        {
            conex.Open();
            string strSQL = @"SELECT DISTINCT
                            SY.YF_DESC_SI                               AS [TIPO MOEDA],
                            RTRIM(SC.C7_PRODUTO) + ' - ' + SC.C7_DESCRI AS PRODUTO,
                            SUM(SC.C7_QUANT)                            AS QTDA, 
                            SUM(SC.C7_TOTAL * SC.C7_TXMOEDA)            AS TOTAL,
                            SUM(SC.C7_TOTAL)                            AS [TOTAL MOEDA]
                   FROM  SC7010 AS SC
                   INNER JOIN SM2010 AS SM WITH (NOLOCK) ON SM.M2_DATA = SC.C7_EMISSAO
                   INNER JOIN SA2010 AS SA WITH (NOLOCK) ON SA.A2_COD = SC.C7_FORNECE
                   INNER JOIN SYF010 AS SY WITH (NOLOCK) ON SY.YF_MOEFAT = SC.C7_MOEDA
                   WHERE SC.D_E_L_E_T_ <> '*' 
 AND SC.C7_EMISSAO BETWEEN CONVERT(datetime, '" + txtDtInicial.Text + "', 103) AND CONVERT(datetime,'" + txtDtFinal.Text + "', 103) AND SA.A2_COD = '" + txtCodFornec.Text + "' GROUP BY SC.C7_PRODUTO, SC.C7_DESCRI, SY.YF_DESC_SI ORDER BY RTRIM(SC.C7_PRODUTO) + ' - ' + SC.C7_DESCRI";

            comando = new SqlCommand(strSQL, conex);

            try
            {
                SqlDataAdapter dados = new SqlDataAdapter(comando);
                DataTable dtLista = new DataTable();
                dados.Fill(dtLista);

                DGW_PedComprasPic.DataSource = dtLista;
            }
            catch
            {
                MessageBox.Show("Não existem dados a serem encontrados");
            }

            double QTDA = 0;
            foreach (DataGridViewRow rowKG in DGW_PedComprasPic.Rows)
            {
                QTDA += Convert.ToDouble(rowKG.Cells["QTDA"].Value);
            }
            txtProdkg.Text = Convert.ToString(QTDA);
            txtProdkg.Text = QTDA.ToString("N2");

            double TotalReal = 0;
            foreach (DataGridViewRow rowR in DGW_PedComprasPic.Rows)
            {
                TotalReal += Convert.ToDouble(rowR.Cells["TOTAL"].Value);
            }
            txtReal.Text = Convert.ToString(TotalReal);
            txtReal.Text = TotalReal.ToString("C");

            conex.Close();
        }

1 answer

0


With LINQ it feels really good to do it, and simple.

decimal totalEuro = DGW_PedComprasPic.Rows.Cast<DataGridViewRow>()
.Where(t => t.Cells[/*Nome ou indice da coluna com o tipo da moeda */].Value.ToString() == "Euro")
.Sum(t => Convert.ToDecimal(t.Cells[/*Nome ou indice da coluna de com o valor */].Value));

txtBoxTotalEuro.Text = totalEuro; // Ajustar para valor monetário.
  • Thank you so much for your attention Alex, but since I’m still new in c# I don’t know where to put your code inside my code above, I’m not able to make work the code you gave me in my code.

  • Place after the conex.Close();. Remember that you have to do this for each type of currency, in my example is the Euro. See also the names I put in my example, adjust them to your need, also remembering that they are case sensitive, the "Euro" that I typed in my example may not work if it is in the wrong format (maisculo/minusculo).

  • Alex did it the way you explained it to me and yet you’re not making the sum no.

  • Does it make a mistake? Remember that the Cast part is like this Cast<DataGridViewRow>() instead of what you posted in your reply Cast().

  • The cast is right in the code, but there is no error not when debugging passes normally but with 0 in txtbox.

  • First change the decimal by double in my code... if it doesn’t work change the Convert.ToDecimal for decimal.Parse also in my code. Maybe it is not able to read the value formatted with dot and comma.

  • Alex good morning, I made all the changes you asked me and still not adding, in your code does not have to be made a foreach to pass line by line in datagridviwer.

  • Confirm that the column containing the currency type ("Euro", "Dolar") is the same zero index, try to put the column name instead of the Dice. Everything indicates that he is not able to find this value "EURO". Also confirm that it is all capital.

  • This all right already test with the column name and also with the column number of the index too, and still no adding up

Show 5 more comments

Browser other questions tagged

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