Thursday 14 March 2013

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.





4 comments:

Setup dev environment for spfx

So lets setup dev environment for SharePoint Framework abbreviated as SPFX. for an Introduction of What is SPFX and What are the capebiliti...