Search code examples
asp.netwebgriddynamic-columns

How to get WebGrid column names dynamically


I have a table which will have a few fixed columns and then a lot of dynamic ones depending upon how the pivot results.

So this works just fine:

@{

    var db = Database.Open("STUDENT");
    var TeacherID = 15313;

    var selectCommand = "PBIS_ReviewBehaviors  @0, @1"; 

    var selectedData0 = db.Query(selectCommand, TeacherID, 0);
    var grid0 = new WebGrid(source: selectedData0, rowsPerPage: 30); 

    List<WebGridColumn> cols0 = new List<WebGridColumn>();

}

and then the body:

<div>
    @grid0.GetHtml(
        tableStyle: "grid",
        headerStyle: "head",
        alternatingRowStyle: "alt"// ,
     //   columns: cols
    )
</div>

however I really want to be able to do some spcific things with some of my fixed columns - in order to do that i need to know who to get the column names in Data0 or Grid0 so then I can build up a list called cols and use it:

something like

foreach (column name in my grid)
{
    if column name = "StudentID"

cols0.Add(grid0.column(    format: @<a href="~/InsertStudent?StudentID=@item.StudentID">Details</a>   );

else

cols0.Add(grid0.column( the column name );

}

Alas I am very new to .net and do not know how I get my list of column names and then use them specifically. I have hopefully made the pseudocode clear enough with my intentions.


Solution

  • You can obtain the columns returned by the database query via the GetDynamicMemberNames method.

    foreach(var item in selectedData0.First().GetDynamicMemberNames()){
        // assumes that the query will always return at least one row
        // will throw an exception if not
        // 'item' represents the column name
    }