Friday, April 19, 2013

Filter Xslt ListView Webpart from Query string varriable

Share point Renders Lists and libraries in XSLT List View Webpart. today , we will see,  How we can filter this list view on  the basis of query string.

Ok , it easy . insert the list on to some page, if you want , or use default view i.e AllItems.aspx.

let us take some example.
supose we have to show news in the website. ok . onto home page probably we want to display news in some custom webpart . these news will be linked to items there may be an option to show all news .

Share Point uses filterfield and filter value combination. for ex. considering avobe point in mind , we may have to display only one record on the basis of id . QueryString will be
?FilterField1=ID&FilterValue1=1
this query string will show item with id 1

similarly we can use filters on any field and on also on several fields.  

How to customize List Field in A Sharepoint List


There are some xsl fiels which are responsible for rendering list views. Main.xsl in layouts declare some global variables such as XmlDefinition  etc.
viewStyle.xsl contains view Styles such as default , boxed etc . other is Fieldtypes.xsl whitch are responsible for rendering particular fields.
Suppose we want to customize a field named TestColumn. In some list.
Lets begin by declaring   xsl declaration
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt"xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"xmlns:asp="http://schemas.microsoft.com/ASPNET/20"xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls"xmlns:ddwrt2="urn:frontpage:internal" xmlns:o="urn:schemas-microsoft-com:office:office">

Now import sharepoint main and internal.xsl
<xsl:include href="/_layouts/xsl/main.xsl"/>
<xsl:include href="/_layouts/xsl/internal.xsl"/>

Several templates are responsible which are in renderview mode ,body mode . as we are going to customize the field text so I can override the template which renders text suppose we have created a column called TestColumn yes/no type We override it as bellow.
<xsl:template name="FieldRef_body.TestColumn" ddwrt:dvt_mode="body"match="FieldRef[@Name='TestColumn']" mode="body" ddwrt:ghost="hide">
    <xsl:param name="thisNode" select="."/>
    <xsl:choose>
    <xsl:when test ="$thisNode/@*[name()=current()/@Name]='Yes'">
      Yes is Writen here
    </xsl:when>
    <xsl:otherwise>
      No Is Writen Here
    </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

full code is bellow.

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt"xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"xmlns:asp="http://schemas.microsoft.com/ASPNET/20"xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls"xmlns:ddwrt2="urn:frontpage:internal" xmlns:o="urn:schemas-microsoft-com:office:office">
      

<xsl:include href="/_layouts/xsl/main.xsl"/>
       <xsl:include href="/_layouts/xsl/internal.xsl"/>
       <xsl:template name="FieldRef_body.Status" match="FieldRef[@Name='Status']"mode="body">
       <xsl:param name="thisNode" select="."/>
              <xsl:choose>
                     <xsl:when test="$thisNode/@*[name()=current()/@Name] = 'Completed'">
                           <img src="/Style Library/en-us/Custom/images/image_cancel_33.png"alt="Status: {$thisNode/@Status}"/>
                     </xsl:when>
                     <xsl:when test="$thisNode/@*[name()=current()/@Name] = 'In Progress'">
                           <img src="/Style Library/en-us/Custom/images/image_cancel_32.png"alt="Status: {$thisNode/@Status}"/>
                     </xsl:when>
                     <xsl:otherwise>
                           <img src="/Style Library/en-us/Custom/images/image_cancel_33.png"alt="Status: {$thisNode/@Status}"/>
                     </xsl:otherwise>
              </xsl:choose>
       </xsl:template>
  <xsl:template name="FieldRef_body.TestColumn" ddwrt:dvt_mode="body"match="FieldRef[@Name='TestColumn']" mode="body" ddwrt:ghost="hide">
    <xsl:param name="thisNode" select="."/>
    <xsl:choose>
    <xsl:when test ="$thisNode/@*[name()=current()/@Name]='Yes'">
      Yes is Writen here
    </xsl:when>
    <xsl:otherwise>
      No Is Writen Here
    </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

Insert webpart >>from webpart properities>>miscellaneous >>xsl link insert the link.

apply the  changes and enjoy.

Bind Sharepoint 2010 Document Library to GridView

Yes guys i am back . with a topic How you can bind a sharepoint document library folders and  files i will also tell you the technique how you can put a meaning full title and then link to file .

very first it will show all the folders then then we can browse the folders. so let us begin our journy by first creating a document library named CompanyDocs. in it create some folders like Design ,Development , Finance. put some files in it.

ok Finaly our Structure is
 CompanyDocs
      >>Design
      >>Development
      >>Finance


yes we have done . now create a webpart drag a gridview on to it.



<asp:GridView  ID="grdDocs" GridLines="None" 
    RowStyle-HorizontalAlign="Center" runat="server"
     Width="100%" AutoGenerateColumns="false"
    AlternatingRowStyle-CssClass="gray_bg" EmptyDataText="There is no records"
     EmptyDataRowStyle-Font-Bold="true" EmptyDataRowStyle-ForeColor="Red"
     EmptyDataRowStyle-HorizontalAlign="Center"
     CssClass="mytableclasse"
    onrowdatabound="grdGroups_RowDataBound" AllowPaging="True"
    onpageindexchanging="grdGroups_PageIndexChanging" PageSize="15">
    <Columns>
    <asp:TemplateField HeaderText="S.No">
    <ItemStyle Width="5%" />
    <ItemTemplate>
    <asp:Label ID="lblsn" runat="server"></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
  
    <asp:TemplateField HeaderText="Title">
    <ItemStyle Width="80%" />
    <ItemTemplate>
    <asp:HyperLink ID="hypfile" runat="server"></asp:HyperLink>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Date">
    <ItemTemplate>
    <asp:Label ID="lblDate" runat="server"></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
 </asp:GridView>
i have taken a grid view and three template fields seriel no , folder or file and Date .

now on cs file see how binding has been done

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }
        private void BindGridView()
        {
        // first impersonate user
            SPSite site=new SPSite(SPContext.Current.Site.ID, SPContext.Current.Web.CurrentUser.UserToken);
            SPWeb web=site.RootWeb;
          
            try
            {
                SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["CompanyDocs"];
                DataTable table=new DataTable();
                table.Columns.Add("Title");
                table.Columns.Add("URL");
                table.Columns.Add("Target");
                table.Columns.Add("Date");
                SPFolder folders=null;
                bool flag=false;
                if (string.IsNullOrEmpty(Request.QueryString["RootFolder"]))
                {
                    folders = docLib.RootFolder;
                    flag = true;
                }
                else
                {
                    folders = web.GetFolder(Request.QueryString["RootFolder"]);
                    flag = false;
                }
                foreach (SPFolder folder in folders.SubFolders)
                {
                    if (flag)
                    {
                        if (folder.Name != "Forms")
                        {
                            SPListItem item = folder.Item;
                            DataRow drfolder = table.Rows.Add();
                            drfolder["Title"] = item["Title"] == null ? folder.Name : item["Title"].ToString();
                            drfolder["URL"] = System.Web.HttpContext.Current.Request.Path + "?RootFolder=" + folder.Url;
                            drfolder["Target"] = "_self";
                            drfolder["Date"] = Convert.ToDateTime(item["Modified"]).ToString("dd/MM/yyyy");
                        }
                      
                    }
                    else
                    {
                        SPListItem item = folder.Item;
                        DataRow drfolder = table.Rows.Add();
                        drfolder["Title"] = item["Title"] == null ? folder.Name : item["Title"].ToString();
                        drfolder["URL"] = System.Web.HttpContext.Current.Request.Path + "?RootFolder=" + folder.Url;
                        drfolder["Target"] = "_self";
                        drfolder["Date"] = Convert.ToDateTime(item["Modified"]).ToString("dd/MM/yyyy");
                    }
                  
                  
                }
                foreach (SPFile file in folders.Files)
                {
                    SPListItem item = file.Item;
                    DataRow drfolder = table.Rows.Add();
                    drfolder["Title"] = item["Title"]==null ? file.Name : item["Title"].ToString();
                    drfolder["URL"] = SPContext.Current.Web.Url + "/" + file.Url;
                    drfolder["Target"] = "_blank";
                
                       drfolder["Date"] = Convert.ToDateTime(item["Created"]).ToString("dd/MM/yyyy");
                  
                }
                grdGroups.DataSource = table;
                grdGroups.DataBind();
            }
            catch(Exception ex)
            {
            }
        }

        protected void grdGroups_RowDataBound(object sender, GridViewRowEventArgs e)
        {
          
           Label  lblsn = e.Row.FindControl("lblsn") as Label;
           HyperLink hypfile = e.Row.FindControl("hypfile") as HyperLink;
           Label lblDate = e.Row.FindControl("lblDate") as Label;

           try
           {
              
               lblsn.Text =(e.Row.RowIndex+1) .ToString();
               hypfile.Text = DataBinder.Eval(e.Row.DataItem, "Title").ToString();
               hypfile.NavigateUrl = DataBinder.Eval(e.Row.DataItem, "URL").ToString();
               hypfile.Target = DataBinder.Eval(e.Row.DataItem, "Target").ToString();
               lblDate.Text = DataBinder.Eval(e.Row.DataItem, "Date").ToString();
          
           }
           catch (Exception ex)
           {
          
           }



        }

        protected void grdGroups_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdGroups.PageIndex = e.NewPageIndex;
            BindGridView();

        }

Just copy and paste avobe cs code in your web part cs file .
see i have impersonate the user to the library
SPSite site=new SPSite(SPContext.Current.Site.ID, SPContext.Current.Web.CurrentUser.UserToken);
if you u do not want use SPContext.Current.Web and AllowUnsafeUpdates to true.

yes insert web part on to some page in the same site as Document Library.
and be happy. all will be fine.