locked
Adding a "total" column to webgrid RRS feed

  • Question

  • User289511288 posted

    Hi all,

    I am trying to find a way to sum up the values in my rows and output it into a single column in WebGrid.

    Was reading http://www.mikesdotnetting.com/article/211/adding-a-footer-to-the-razor-webgrid 

    I keep getting an Invalid Column error and  can't figure out why the "Total" column won't auto-create.

    Tried another method using SELECT statement SQL to push the value into DB but still i'm not getting the value output in the WebGrid.

    Here is a copy of my code

    @{
    
    
        var db = Database.Open("StarterSite");
        var selectCommand = "SELECT * FROM ValAdd";
    
        <!-- column total coding here-->
        var calcval = db.Query(selectCommand).Select(o => new SelectListItem
        {
            Value = o.Id.ToString(),
            Text = o.ID.ToString(),
            Selected = o.ID.ToString() == Request["ID"]
        });
        var valTotal = 0f;
        if (IsPost)
        {
            selectCommand = @"SELECT o.invacc, o.lti, o.overtime, (o.invacc + o.lti + o.overtime) as calcval FROM ValAdd o where o.ID = @0";
            var calcDetails = db.Query(selectCommand, Request["ID"]);
            valTotal = calcDetails.Sum(o => (float)o.calcval);
        }
        <!-- column total coding here-->
    
        var selectedData = db.Query(selectCommand);
        var grid = new WebGrid(source: selectedData, defaultSort: "invacc", rowsPerPage: 3); //source is data drawn, change rows shown in page
    
    }
    
    <body>
        <form method="get">
            <fieldset>
                    @grid.GetHtml(
               tableStyle: "grid",
               headerStyle: "head",
               alternatingRowStyle: "alt",
               columns: grid.Columns(
    grid.Column("invacc", "Accuracy),               
    grid.Column("calcval")                                                                
                   )
                )
                </fieldset>
        </form>
    </body>
    </html>

    Thanks all!

    Wednesday, November 16, 2016 7:44 AM

All replies

  • User-846834550 posted

    Check grid is null.

    @if(grid != null){
      
    }

    Monday, November 21, 2016 1:17 AM
  • User1847352307 posted

    Use following code for adding a total column to webgrid.

     

    @grid.GetHtml(

    columns: grid.Columns(

        grid.Column(

            header: "invacc",

            format: (item) => { @: @item.invacc}

            ),

    grid.Column(

            header: "Accuracy",

            format: (item) => { @: @item.Accuracy}

            )

    grid.Column(

            header: "calcval",

            format: (item) => { @: @item.calcval}

            )

        )

    )

    Thursday, November 24, 2016 8:23 AM