Saturday, 31 August 2013

Programmatically create a Attachment functionality in Custom Visual WebPart Sharepoint 2010

i modified it to suit my requirement

paste this code in the .aspx  page
<table> <tr><td>
<asp:HiddenField Value="hDeleteAttachs" ID="hHiddenFields"  runat="server" />
</td></tr>

<tr>
<td><span id="part1">
<SharePoint:AttachmentButton runat="server" ID="btnAttach" ControlMode="new" Text="Add Attachment">
</SharePoint:AttachmentButton> </span></td></tr>

<tr><td id='idAttachmentsRow'>
<SharePoint:AttachmentUpload runat="server" ID="uploadAttach" ControlMode="New">
</SharePoint:AttachmentUpload></td></tr>

<tr><td><SharePoint:AttachmentsField runat="server" ID="fieldAttach" ControlMode="new" FieldName="Attachments">
</SharePoint:AttachmentsField></td></tr>
</table>

 <asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submitButton_Click" />

Below in the c# page

namespace ProjectName.VisualWebPartName
{
    public partial class VisualWebPartNameUserControl: UserControl
    {

        SPSite Osite = null;
        SPWeb Oweb = null;
        SPSite noprevsite = null;
        SPWeb noprevweb = null;
        SPList Olist = null;
        SPListItem Osplistitem = null;

 protected void Page_Load(object sender, EventArgs e)
        {
             noprevsite = SPContext.Current.Site;
             noprevweb = noprevsite.OpenWeb();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Osite = new SPSite(noprevsite.ID);
                Oweb = Osite.OpenWeb(noprevweb.ID);
                Oweb.AllowUnsafeUpdates = true;
                Olist = Oweb.Lists["ListName"];
                btnAttach.ListId = Olist.ID;
                uploadAttach.ListId = Olist.ID;
                fieldAttach.ListId = Olist.ID;
                Osplistitem = Olist.Items.Add();
});
}

 protected void submitButton_Click(object sender, EventArgs e)
        {
          AddAttachments(ref Osplistitem);
        }
   void AddAttachments(ref SPListItem Osplistitem)
        {
            try
            {
                for (int i = 0; i < (Page.Request.Files.Count - 1); i++)
                {
                    try
                    {
                        //Get the list of files for attachments
                        HttpPostedFile newAttach = Page.Request.Files[i];
                        byte[] fileContents = new byte[newAttach.ContentLength - 1];
                        newAttach.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        newAttach.InputStream.Read(fileContents, 0, newAttach.ContentLength - 1);
                        System.IO.FileInfo fInfo = new System.IO.FileInfo(newAttach.FileName);
                        Osplistitem.Attachments.Add(fInfo.Name, fileContents);
                    }
                    catch { continue; }
                }
            }
            catch
            {
            }

        }
}
}

No comments:

Post a Comment