Saturday, March 20, 2010

Using SPGridview - Sample Application

using System;
using System.Runtime.InteropServices;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SPGridViewTest
{
[Guid("a8737f22-bacf-40db-806e-51c81a9b09d8")]
public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
{
public WebPart1()
{
}
private SPGridView oGrid;

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
SPWeb site = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context);

SPList taskList = site.Lists["Department"];

SPDataSource mySPDS = new SPDataSource();

mySPDS.List = taskList;

//You could also just create a datatable here and populate it from some other source like so...

//DataTable dt = new DataTable();
//dt.Columns.Add("Title");
//DataRow dr = dt.NewRow();
//dr["Title"] = "My Test Item";
//dt.Rows.Add(dr);

this.oGrid.DataSource = mySPDS;

//Use the line below if you are binding to the datatable...

//this.oGrid.DataSource = dt;

this.oGrid.DataBind();
base.Render(writer);

}
protected override void CreateChildControls()
{
this.oGrid = new SPGridView();

this.oGrid.AutoGenerateColumns = false;


HyperLinkField hyperFieldID = new HyperLinkField();
string[] IDarray = new string[1];
IDarray[0] = "ID";
hyperFieldID.DataTextField = "ID";
hyperFieldID.HeaderText= "ID";
hyperFieldID.DataNavigateUrlFields = IDarray;
//hyperFieldSName.DataNavigateUrlFormatString = "{0}";
hyperFieldID.DataNavigateUrlFormatString = "~/Lists/Department/EditForm.aspx?ID={0}";

BoundField colTitle = new BoundField();
colTitle.DataField = "Title";
colTitle.HeaderText = "Title";

//BoundField colSName = new BoundField();
//colSName.DataField = "SName";
//colSName.HeaderText = "SName";
BoundField SName = new BoundField();
SName.DataField = "SName";
SName.HeaderText="Name";

//HyperLinkField hyperFieldSName = new HyperLinkField();
//string[] SNamearray = new string[1];
//SNamearray[0] = "SName";
//hyperFieldSName.DataTextField = "SName";
//hyperFieldSName.DataNavigateUrlFields = SNamearray;
////hyperFieldSName.DataNavigateUrlFormatString = "{0}";
//hyperFieldSName.DataNavigateUrlFormatString = "~/Lists/Department/EditForm.aspx?ID={0}";

this.oGrid.Columns.Add(hyperFieldID);
this.oGrid.Columns.Add(colTitle);
//this.oGrid.Columns.Add(hyperFieldSName);
this.oGrid.Columns.Add(SName);

this.Controls.Add(this.oGrid);
base.CreateChildControls();
}
}
}