0

enter code hereHello I try to convert the dataitem into decimal array, here is my code;

 if (e.Row.RowType == DataControlRowType.DataRow)
        {

            for (; i < 9; )
                {


                    if (!DBNull.Value.Equals(DataBinder.Eval(e.Row.DataItem, headerNames[i])))
                        TotalSales += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, headerNames[i]));
                totals(e.Row.DataItem);
                }

                       }

    }
    public static decimal[] totals(object arr)
    {
        decimal[] res = arr as decimal[];
        decimal[] sRes = res.OfType<decimal>().ToArray();
        return sRes;


    }

I can see that the dataitem successfully assigned to arr. However the line

decimal[] res = arr as decimal[]; does not assign the arr to res, so the next line gives me an error complaining the value cannot be null.

Can you please help?

1 Answers1

0

While I was waiting for an answer here, I tried and came up with a code that calculates totals in GridView_DataBound event, please comment if there is anything can be better and how to not show the total (0.0) under the columns that do not have decimal values (i.e. string)

public static void gridViewTotals1(object sender , EventArgs e)
{
    var grdview = (GridView)sender;
    decimal[,] rowAndColumns = new decimal[grdview.Rows.Count, grdview.Columns.Count];
    decimal n;
    decimal[] totalSalesArray = new decimal[grdview.Columns.Count];
    for (int i = 0; i < grdview.Columns.Count; i++)
    {
        for (int j = 0; j < grdview.Rows.Count; j++)


            if (decimal.TryParse(grdview.Rows[j].Cells[i].Text, out n))
            {
                rowAndColumns[j, i] = Convert.ToDecimal(grdview.Rows[j].Cells[i].Text);
            }

    }
    GridViewRow footerRow = grdview.FooterRow;

    for (int k = 0; k < grdview.Columns.Count; k++)
    {
        decimal totalSales = 0;
        for (int l = 0; l < grdview.Rows.Count; l++)
        {
            totalSales += rowAndColumns[l, k];
            totalSalesArray[k] = totalSales;

            footerRow.Cells[k].Text = String.Format("{0:N2}", totalSales);
        }

    }

}