visual-studio-2010sharepointdatatableweb-partssplist

Populating a GridView table in VS2012 as webpart with SPList Only Title column has value


I am trying to populate a gridview table with a list from a SP2010 website as a webpart to be used on a different SP site. So far the code I have is:

    SPSite mySite = new SPSite("Sharepoint list URL ");
        SPWeb myweb= mySite.OpenWeb();
        SPList myList = myweb.Lists["ListName"];
        SPListItemCollection items = myList.Items;


                    DataTable table;
                    table = new DataTable();
                    table.Columns.Add("Title", typeof(string));
                    table.Columns.Add("First Name", typeof(string));
                    table.Columns.Add("Last Name", typeof(string));


                    DataRow row;
                    foreach (SPListItem item in items)
                    {
                        row = table.Rows.Add();
                        row["Title"] = item.Name;

                    }
                    GridView2.DataSource = table.DefaultView;
                    GridView2.DataBind();

I've tried adding First name and last name to various other locations in the code but to no success. I end up with a table on the website produced by the webpart but it only has the title column with the correct values displayed and then two columns with the titles I added but no values inside. Thank you for your time in considering my issue.


Solution

  • You can use the SPListItemCollection directly as a datasource for a GridView.

    There is no need to create the DataTable.

    Just do it like this

    SPSite mySite = new SPSite("Sharepoint list URL ");
    SPWeb myweb= mySite.OpenWeb();
    SPList myList = myweb.Lists["ListName"];
    SPListItemCollection items = myList.Items;
    
    GridView2.DataSource = items.GetDataTable();
    GridView2.DataBind();
    

    Just bind the columns you want to display and you are done.