Search code examples
c#asp.netsharepointdatatablespgridview

Loading data form DataTable to SPGridview C#


I'm making some webparts for myself and I want to populate SPGridview with some data.

DataTable table = /*some data*/;
SPGridview grid = new SPGridview();

// setting up SPGridview properties 

grid.DataSource = table;
grid.DataBind();

When I did that with GirdView it worked just fine. But when I tried to do that with SPGridview my webpart shows just blank page. I suppose that SPGridview need a little more from my side and if you could give me tip how to do it.


Solution

  • For some reason Microsoft disabled AutoGenerateColumns property and I don't know how to bypass without using a loop. Here is a working code:

            SPGridView _gridview = new SPGridView();
            DataTable table = /*some data*/;
    
            _gridview.Enabled = true;
            _gridview.AutoGenerateColumns = false;
            _gridview.Visible = true;
    
            foreach(DataColumn col in table.Columns)
            {
                SPBoundField field = new SPBoundField();
                field.DataField = col.ColumnName;
                _gridview.Columns.Add(field);
            }
    
            _gridview.DataSource = table;
            _gridview.DataBind();
    
            this.Controls.Add(_gridview);