Wednesday, October 30, 2013

Display document library items into gridview of asp.net page to make it available for downloading the documents

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using Microsoft.SharePoint.Utilities;

namespace BursaryVisualWebpart.BursaryCaseID_DocumentsVisualWebpart
{
    public partial class BursaryCaseID_DocumentsVisualWebpartUserControl : UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                    {
                        string bursaryapp = Request.QueryString["Folio"];

                                  SPList document = web.Lists["Requirement"];
                                  SPQuery query = new SPQuery();
                                  query.Query = "<Where><Eq><FieldRef Name='ReferenceNumber'/><Value Type='Text'>" + bursaryapp + "</Value></Eq></Where>";
                                  SPListItemCollection objItemcoll = document.GetItems(query);
                                  DataTable itemsDataTable = objItemcoll.GetDataTable();
                                  GridView1.DataSource = itemsDataTable;
                                  GridView1.DataBind();


                    }

                }
            });

        }


        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton hypLink = (LinkButton)e.Row.Cells[3].Controls[1];
                hypLink.CommandArgument = e.Row.RowIndex.ToString();


            }
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            try
            {
                if (e.CommandName == "download")
                {
                    string filename = e.CommandArgument.ToString();
                    GridView gv = this.GridView1;
                    HyperLink hypLink = (HyperLink)gv.Rows[Convert.ToInt32(e.CommandArgument)].Cells[0].Controls[1];


                    SPWeb web = SPContext.Current.Web;
                    web.AllowUnsafeUpdates = true;


                    string url = web.Url + hypLink.NavigateUrl;

                    SPFile tempFile = web.GetFile(url);


                    byte[] obj = (byte[])tempFile.OpenBinary();



                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.BufferOutput = true;
                    Response.AddHeader("Content-Type", "Application/octet-stream");

                    Response.AddHeader("Content-Length", obj.Length.ToString());
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + hypLink.Text);
                    Response.BinaryWrite(obj);
                    Response.Flush();
                    Response.End();
                    web.AllowUnsafeUpdates = false;
                }



            }
            catch (Exception ex)
            {
                SPContext.Current.Web.AllowUnsafeUpdates = false;

            }
        }


    }



}

..........................................................................................
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="BursaryCaseID_DocumentsVisualWebpartUserControl.ascx.cs" Inherits="BursaryVisualWebpart.BursaryCaseID_DocumentsVisualWebpart.BursaryCaseID_DocumentsVisualWebpartUserControl" %>
<script type="text/javascript">

    function setFormSubmitToFalse() {

        if (_spFormOnSubmitCalled) {
            _spFormOnSubmitCalled = false;
        }

    }
</script>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    EnableModelValidation="True"  onrowcommand="GridView1_RowCommand" OnRowCreated="GridView1_RowCreated">
    <Columns>
       <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:HyperLink ID="HyperLink1" runat="server"
                    NavigateUrl='<%# Eval("FileLeafRef", "/Requirement/{0}") %>' Target="_parent"
                    Text='<%# Eval("FileLeafRef") %>' ></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
       <%-- <asp:HyperLinkField DataTextField="FileLeafRef" HeaderText="Name" DataNavigateUrlFields="FileLeafRef"  Target="_parent" DataNavigateUrlFormatString="/Req/{0}" />--%>

        <asp:BoundField DataField="ReferenceNumber" HeaderText="ReferenceNumber" />
     <asp:BoundField DataField="ApplicantFullName" HeaderText="ApplicantFullName" />
      <asp:TemplateField HeaderText="Download">
            <ItemTemplate>
            <asp:LinkButton runat="server" ID="lnk" CommandName="download"    OnClientClick="setFormSubmitToFalse();">Download </asp:LinkButton>


            </ItemTemplate>
        </asp:TemplateField>


    </Columns>
</asp:GridView>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

No comments:

Post a Comment