ASP.NET GridView to List with headers

I would like to convert my GridView to a list with the headers as the first row.

This can convert my GridView into a list without headers.

var Result = GridView.Rows.OfType<GridViewRow>().Select(
                        r => r.Cells.OfType<TableCell>().Select(c => c.Text).ToArray()).ToList();

I am trying this to convert it back with the headers.

var myorgitem = GridView.Rows.OfType<GridViewRow>().Select(
                    r => r.Cells.OfType<TableCell>().ToDictionary(
                        c => ????????????????????, c => (c.Text ?? "").ToString())).ToList();

Thank you!


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This works for now, but I would love to make it shorter and more efficient. This will convert any Gridview to a list with headers as the first row.

protected List<string[]> GridViewToList(GridView gv)
        var mylist = gv.Rows.OfType<GridViewRow>().Select(
                    r => r.Cells.OfType<DataControlFieldCell>().Select(
                        c => c.ContainingField.HeaderText).ToArray()).ToList();
        if (mylist.Count > 1)
            mylist.RemoveRange(1, mylist.Count - 1);

                    r => r.Cells.OfType<DataControlFieldCell>().Select(c => c.Text).ToArray()).ToList());
        return mylist;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x