Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Thursday, February 16, 2012

Bindings Top five Announcements to SpGridView without a Single line of Loop

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 System.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Text;
using System.Data;
[assembly:AllowPartiallyTrustedCallers]
namespace SampleWebPart1
{
    [Guid("64f3abf3-d56d-40d1-8847-2aa74a6612ad")]
    public class SampleWebPart1 : System.Web.UI.WebControls.WebParts.WebPart
    {
        public SampleWebPart1()
        {
        }
        SPGridView sgvAnnouncements;
        string strError = string.Empty;
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(strError);
            try
            {
                sgvAnnouncements.RenderControl(writer);
            }
            catch (Exception ex)
            {
                writer.Write(ex.ToString());
            }
        }
        protected override void CreateChildControls()
        {
            try
            {
                sgvAnnouncements = new SPGridView();
                sgvAnnouncements.ID = "sgvAnnouncements";
                sgvAnnouncements.AutoGenerateColumns = false;
                this.Controls.Add(sgvAnnouncements);

                BoundField bTitle = new BoundField();
                bTitle.HeaderText = "Title";
                bTitle.DataField = "Title";
                sgvAnnouncements.Columns.Add(bTitle);

                BoundField bCreatedBy = new BoundField();
                bCreatedBy.HeaderText = "Created By";
                bCreatedBy.DataField = "Author";
                sgvAnnouncements.Columns.Add(bCreatedBy);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWeb currentWeb = SPContext.Current.Web;
                    SPQuery sQuery = new SPQuery();
                    sQuery.Query = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy><Where><Geq><FieldRef Name='Expires' /><Value Type='DateTime'><Today /></Value></Geq></Where>";
                    sQuery.RowLimit = 5;
                    SPList lstAnnouncements = currentWeb.Lists["Announcements"];
                    SPListItemCollection myColl = lstAnnouncements.GetItems(sQuery);
                    if (myColl.Count > 0)
                    {
                        sgvAnnouncements.DataSource = myColl.GetDataTable();
                        sgvAnnouncements.DataBind();
                    }
                });
            }
            catch (Exception ex)
            {
                strError += ex.ToString();
            }



        }
    }
}


No comments:

Post a Comment