CustomCodes‎ > ‎

SP context custom webpart sample format

// to be done in CS file (code behind)
 
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
 
namespace LMEX.WebParts.WebParts.SampleCustomWebPart
{
    public partial class SampleCustomWebPart: UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {               
                SPWeb oRootWeb = SPContext.Current.Site.RootWeb;              
                string strSiteUrl = SPContext.Current.Site.Url + "/" + strSubSiteUrlName;
 
                using (SPSite oSite = new SPSite(strSiteUrl))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList list = oWeb.Lists.TryGetList(myListName);
 
                        if (list != null)
                        {                           
                            SPQuery query = new SPQuery();                         
                            query.Query = @"<Where>...CAML Query Goes Here...</Where><OrderBy>...Ordering Goes Here...</OrderBy>";
                            query.ViewAttributes = "Scope=\"RecursiveAll\"";
                            query.RowLimit = 5;
                            SPListItemCollection itemcollection = list.GetItems(query);
                            int intItemCount = itemcollection.Count;
                            foreach (SPListItem item in itemcollection)
                            {
                               // Use item value as:
                              string abc = item["ColumnName"];
 
                               // do other stuffs..
                            }
                           
                        }
                    }
                }
            }
 
            catch (Exception ex)
            {
                Logger.LogException(ex, "CustomWebPart-Logs : Page_Load()");
            }
        }
    }
}