简体   繁体   中英

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.

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
}

thank you !

the workable solution was:

try 
{    
    foreach(var i in selectedData0.First().GetDynamicMemberNames() ) 
    {
        if(i == "StudentID") {
            cols0.Add(grid0.Column(format: @<a href="~/DetailStudent?StudentID=@item.StudentID">Details</a>) );
        }
        else {
            cols0.Add(grid0.Column(i.ToString())  );
        }
    }
}
catch {}

This replaced my first column with a link to another page and kept the rest dynamic to what was returned. Because it possible to have no rows returned I put in the try / catch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM