Saturday, October 12, 2013

List Item Attachments in Gridview

This code snippet for showing the SharePoint List Item's attachment collection in a ASP.NET. Build your ASP.NET grid view with columns and a Link to delete the selected rows value. Here I am listing out the few files and wanted to allow the user to delete the file by clicking the link. Here is code to retrieve the selected row index and its cell value.
 public void LinkAction(object sender, EventArgs e)
        {


            LinkButton lnkbtn = sender as LinkButton;
            GridViewRow selectedRow = lnkbtn.NamingContainer as GridViewRow;

            int a = selectedRow.RowIndex;
            string txt = selectedRow.Cells[2].Text.ToString();
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    var list = web.Lists["Region"];
                    web.AllowUnsafeUpdates = true;
                    SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders["5"];
                    SPFile file = web.GetFile(web.Url +"/"+folder+"/" + txt);
                    file.Delete();
                    web.Update();
                    web.AllowUnsafeUpdates = false;
                }

            }
  
Grid View Markup










Binding the Grid view with List Item's attachments.
    public List GetAttachments()
        {
            List fNAme = new List();
            
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        string sp = string.Empty;
                        var list = web.Lists["Region"];
                        SPListItem item = list.GetItemById(5);
                        SPAttachmentCollection cols = item.Attachments;
                        SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders[item.ID.ToString()];
                        FileDetails f = null;
                        foreach (SPFile file in folder.Files)
                        {
                            f = new FileDetails();
                            f.fName = file.Name;
                            f.fUrl = web.Url + "/" + folder.ToString() + "/" + file.Name;
                            fNAme.Add(f);

                        }

                    }

                }
            
            return fNAme;
        }
For Getter and Setter and FileDetails Class code available on my previous post.