Displaying Sharepoint Custom List items in SPGridView

14 July, 2009 (17:08) | MOSS - Object Model | By: GVK

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

Comments

Pingback from Export SPGridView to Excel spreadsheet in Sharepoint 2007
Time July 28, 2009 at 8:39 am

[...] In my last post I have show you how to retrieve current user profile in Sharepoint 2007, beofre that I have also posted on how to display custom list items in SPGridView [...]

Comment from Venkat
Time February 8, 2010 at 10:46 am

If only i need to display cities are belong to india.How to use query in the listed data eg: when country=’india’

Write a comment