Thursday, July 21, 2011

Create a Application Page with code behind

We can create an application page using inline code but I think its more elegant to use code behind.
I am using WSPbuilder for the project.The solution structure
Some things to be taken care of in the aspx page are
  • Get Full Assembly name information
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="codeBehindPage.codeBehindPage,codeBehindPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=afd867e29b3b4c59" %>

<asp:content  contentplaceholderid="PlaceHolderMain" runat="server">
<asp:button id="Button1" onclick="Button1_Click" runat="server" text="Button"/>
<br/>
<asp:GridView ID="gv" runat="server"/>
<asp:Content>

And now the code Behind for the button click event.
Important things to note
General Tendency is to get item from SharePoint List using the SPListItemCollection and bind to the GridView as it can understand the collections and display in tabular format which is where it gives the famous error irrespective of the collection containing results
Value does not fall within the expected range.   at Microsoft.SharePoint.SPFieldMap.GetColumnNumber(String strFieldName)
   at Microsoft.SharePoint.SPListItemCollection.GetRawValue(String fieldname, Int32 iIndex)
   at Microsoft.SharePoint.SPListItem.GetValue(SPField fld, Int32 columnNumber, Boolean bRaw)
   at Microsoft.SharePoint.SPListItem.GetValue(String strName, Boolean bThrowException)
   at Microsoft.SharePoint.SPListItem.get_Name()


So the best way to deal is as shown below

namespace codeBehindPage
{
    public partial class codeBehindPage : System.Web.UI.Page
    {      
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SPWeb site = SPContext.Current.Web;
            SPList list = site.Lists["Customer Service Events"];
            SPQuery query = new SPQuery();
            query.Query = "";
            query.ViewFields = "";
                //""+
            SPListItemCollection itemcol = list.GetItems(query);

            gv.DataSource = list.GetItems(query).GetDataTable();
            //gv.DataSource = list.GetItems(query);
            gv.DataBind();
        }
    }
}

No comments:

Post a Comment