locked
Dynamically add web grid columns from a dynamic pivot query result RRS feed

  • Question

  • User325035487 posted

    My pivot query returns dynamic columns. I searched and found the following solution by mike brind

    http://stackoverflow.com/questions/24517701/how-to-get-webgrid-column-names-dynamically. Based on that my code like this

    var ovrd_data = db.Query(sql_ovrd);
        var grid = new WebGrid(ovrd_data, canPage: false, rowsPerPage: 100, ajaxUpdateContainerId: "grid");
        List<WebGridColumn> cols0 = new List<WebGridColumn>();
        if (ovrd_data.FirstOrDefault() != null)
        {
            foreach (var r in ovrd_data.First().GetDynamicMemberNames())
            {
                // assumes that the query will always return at least one row
                // will throw an exception if not
                // 'item' represents the column name
                if (r == "OVRCATEGORY")
                {
                    cols0.Add(grid.Column(r.ToString())); 
                }
                else if (r.ToString().Contains("MH-"))
                {
                    int hiid = db.QueryValue("SELECT ID FROM Hals WHERE Name=@0", r);
                    cols0.Add(grid.Column(format: @<a href="~/reakdown/@year/@item.CatID?hid=@hiid">@item[r]</a>, style: "monthcol"));
                }
            }
        }

    Everything works fine but my dynamic columns doesnt get a title.

    so i changed the code like this

                else if (r.ToString().Contains("MH-"))
                {
                    int hiid = db.QueryValue("SELECT ID FROM Hals WHERE Name=@0", r);
                    cols0.Add(r,grid.Column(format: @<a href="~/reakdown/@year/@item.CatID?hid=@hiid">@item[r]</a>, style: "monthcol"));
                }

    I passed in the column name as "r". This gives an error

    error CS1978: Cannot use an expression of type 'lambda expression' as an argument to a dynamically dispatched operation

    Any help is appreciated.

    Friday, November 27, 2015 9:59 AM

Answers

  • User325035487 posted

    Ok looks like i ran for help too soon

                else if (r.ToString().Contains("MH-"))
                {
                    string columnname = r; 
                    int hiid = db.QueryValue("SELECT ID FROM Hals WHERE Name=@0", r);
                    cols0.Add(grid.Column(columnname,format: @<a href="~/reakdown/@year/@item.CatID?hid=@hiid">@item[r]</a>, style: "monthcol"));
                }

    Solved it like that. Hope this helps some one.. Thank you

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 27, 2015 10:04 AM