简体   繁体   中英

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.

        SPGridView myGridView = new SPGridView();
        myGridView.Enabled = true;

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


       this.Controls.Add(myGridView);

Try this code............

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);

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