Search code examples
c#asp.netgridviewaspxgridview

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!


Solution

  • 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);
    
            mylist.AddRange(gv.Rows.OfType<GridViewRow>().Select(
                        r => r.Cells.OfType<DataControlFieldCell>().Select(c => c.Text).ToArray()).ToList());
            return mylist;
        }