Displaying Sharepoint Custom List items in SPGridView
Here is a simple SPGridView example, which displays rows from a Sharepoint Custom List.
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
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’
Comment from Kunal Jaiswal
Time May 31, 2010 at 9:50 pm
Thanks frnd. Gud Codes for Fresher’s Point of View.
Comment from thesharepointmarket
Time October 31, 2010 at 6:48 pm
Great webpart!
Why dont you put it on sale and earn some bucks. Visit
Submit Your WebPart
and start earning!
Comment from Cool Person
Time July 21, 2011 at 5:12 pm
What if I like to render the SPGridView in button click event but not in the page load???
Can you help? Very first time when I click the button everything working as expected. But, sorting, filtering not working as data is not binding every time…..



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 [...]