Using SPGridView to Display list Data WebPart

In this example, SharePoint's SPGridView control is used to display List Data in a Custom webpart. The webpart is created using VseWss and it uses a Custom list called "Clients". A Custom Column named "ClientsName" is displayed in the Spgridview as output.

OutPut :


Code :

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace MyCustomWebPart
{
[Guid("f66be37b-91f9-4e99-97dc-0e30f6eb44ff")]
public class MyCustomWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
SPGridView myGrid;

public MyCustomWebPart()
{
}

protected override void CreateChildControls()
{
base.CreateChildControls();
SPDataSource SPDataSource1 = new SPDataSource();
try
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();

//Using RunWithElevatedPrivileges

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(mySite.ID))
{
using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{
myGrid = new SPGridView();
myGrid.AutoGenerateColumns = false;

BoundField ClientName = new BoundField();
ClientName.HeaderText = "Our Clients";
ClientName.DataField = "ClientsName";
myGrid.Columns.Add(ClientName);

SPList List = myWeb.Lists["Clients"];
SPDataSource1.List = List;

myGrid.DataSource = SPDataSource1;
myGrid.DataBind();

Controls.Add(myGrid);}}
});
}
catch { }}
}
}

2 comments:

  1. See the sharepoint gridview advaned webpart @
    http://www.thesharepointmarket.com/2010/11/configurable-sharepoint-gridview-webpart/

    ReplyDelete
  2. How can I edit a list using SPGridView? Please give me an example similar to the code above if possible.

    Thanks, Ann

    ReplyDelete

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com