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;
usingMicrosoft .SharePoint;
usingMicrosoft .SharePoint.WebControls;
usingMicrosoft .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 { }}
}
}
OutPut :
Code :
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using
using
using
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 { }}
}
}
See the sharepoint gridview advaned webpart @
ReplyDeletehttp://www.thesharepointmarket.com/2010/11/configurable-sharepoint-gridview-webpart/
How can I edit a list using SPGridView? Please give me an example similar to the code above if possible.
ReplyDeleteThanks, Ann