Displaying Sharepoint Custom List items in SPGridView

Here is a simple SPGridView example, which displays rows from a Sharepoint Custom List.

Custom List
Custom List
Displaying custom list rows in SPGridView
Displaying custom list rows in SPGridView

Download complete source code

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace FiveNumber
{
    [Guid("e6a48f2e-8f31-4738-8ed6-6629f985956d")]
    public class DisplayListInSpGridView : System.Web.UI.WebControls.WebParts.WebPart
    {
        SPGridView myGridView;
        SPDataSource myDataSource = new SPDataSource();

        protected override void CreateChildControls()
        {
            myGridView = new SPGridView();
            myGridView.Enabled = true;
            myGridView.AutoGenerateColumns = false;
            myGridView.ID = "gv_MyGridView";

            myGridView.AllowGrouping = true;
            myGridView.AllowGroupCollapse = true;
            myGridView.GroupField = "Country";
            myGridView.GroupDescriptionField = "Country";
            //myGridView.GroupFieldDisplayName = "Country Name";

            BoundField colTitle = new BoundField();
            colTitle.DataField = "Country";
            colTitle.HeaderText = "Country";
            this.myGridView.Columns.Add(colTitle);

            BoundField colMission = new BoundField();
            colMission.DataField = "State";
            colMission.HeaderText = "State";
            this.myGridView.Columns.Add(colMission);

            this.Controls.Add(myGridView);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Countries"];
            myDataSource.List = list;
            myGridView.DataSource = myDataSource;
            myGridView.DataBind();            

            myGridView.RenderControl(writer);
        }
    }
}