Loading...

Sunday, April 11, 2010

Querying The List of SharePoint With ServerTemplate ID and Display the result in SPGridView

Create a webpart and initialize the SPGridView control


private SPGridView grid;

protected override void CreateChildControls() {
base.CreateChildControls();
// create and add the gridview control
this.grid = new SPGridView();
this.grid.AutoGenerateColumns = false;
this.Controls.Add(this.grid);
}


On PreRender Query list ServerTemplate ID
for contact list as follows

protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
SPWeb site = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();

query.Lists = @"<lists servertemplate="105">"
      query.ViewFields = @"<fieldref name="ID">" + <br />
                          "<fieldref name="FirstName">" +
                          "<fieldref name="Title">";
     
      query.Webs = @"<webs scope="Recursive">";


DataTable dtResults = site.GetSiteData(query);
DataView dv = new DataView(dtResults);

// set up the field bindings
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = "Last Name";
boundField.DataField = "Title";
this.grid.Columns.Add(boundField);

boundField = new SPBoundField();
boundField.HeaderText = "First Name";
boundField.DataField = "FirstName";
this.grid.Columns.Add(boundField);

this.grid.AutoGenerateColumns = false;
this.grid.DataSource = dv;
this.grid.DataBind();

this.grid.AllowSorting = true;
this.grid.HeaderStyle.Font.Bold = true;

}