Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm populating an MVC WebGrid with data from a schema which is unknown at design time. It's all working fine, although I'm struggling with formatting the data. I just don't know the syntax to set a property of type Func<object, object>.

In the controller
C#
var fields = GetListOfFieldsFromDB();
foreach (var f in fields)
{
    var c = new System.Web.Helpers.WebGridColumn();
    c.ColumnName = f.FieldName;
    c.Header = f.FieldAlias;
    c.CanSort = true;
    switch (f.SqlDataType)
    {
        case "datetime":
            c.Format = (item) => string.Format("{0:dd MMM yyyy}", 
                             item.DontKnowTheNameOfTheFieldYet; // Need help here . 
            break;

        case "decimal":
            c.Format = item => item.ToString("C"); // Need more help here. 
                                                   // No clue what the syntax should be.
            break;

         // some more formats here
         ...
     }

   columnList.Add(c);
}


In the view
C#
var grid = new WebGrid(source: Model.Records, canPage: true, rowsPerPage: 20);
@grid.GetHtml(tableStyle: "table", columns: Model.Columns)


What I have tried:

c.Format = item => item.ToString("C"); //doesn't work
Posted
Updated 19-Jun-17 6:11am
v3

1 solution

Try using the indexer:
C#
switch (f.SqlDataType)
{
    case "datetime":
        c.Format = item => string.Format("{0:dd MMM yyyy}", item[f.FieldName]);
        break;
    
    case "decimal":
        c.Format = item => item[f.FieldName].ToString("C");
        break;
 
    ...
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900