1

I have a list, ListPersonalDetails, for storing personal details of students. It has fields like firstName, lastname, address etc. It also contains a field to store the photo which is of type image. I created a visual webpart, StudentPersonalDetails, to add items to ListPersonalDetails. It contains a file upload control used to browse photo. I need to upload the image along with other details to the list. I am using Visual Studio 2010 for my SharePoint site development completely.

used the following code part to update the list:

SPListItem studentDetailsItem = SPContext.Current.Web.Lists["Student Details"].Items.Add();
        studentDetailsItem["StudentID"] = Guid.NewGuid();
        studentDetailsItem["FirstName"] = txtFirstName.Text;
        studentDetailsItem["LastName"] = txtLastName.Text; 
        //studentDetailsItem["photo"]=need to upload photo
        studentDetailsItem.Update();

Any help on this is highly appreciated.

2 Answers 2

1

To your Visual Webpart Ascx page, add a File upload control:

<asp:FileUpload ID="FileUploadAttachment" runat="server" />

And in your update function, you can upload the attachment by:

            SPListItem studentDetailsItem = SPContext.Current.Web.Lists["Student Details"].Items.Add();
            studentDetailsItem["StudentID"] = Guid.NewGuid();
            studentDetailsItem["FirstName"] = txtFirstName.Text;
            studentDetailsItem["LastName"] = txtLastName.Text; 


            //------------------------------------------------------------
            // If file selected, save to list
            if (FileUploadAttachment.HasFile == true)
            {
                SPAttachmentCollection attach = studentDetailsItem.Attachments;
                String fileName = FileUploadAttachment.PostedFile.FileName;
                byte[] textfile = FileUploadAttachment.FileBytes;
                attach.Add(fileName, textfile);

            }
            // ------------------------------------------------------------

            studentDetailsItem.Update();
0

It would probably be best to enable attachments on the list and the store the image as an attachment. See SPAttachmentCollection

1
  • I have file upload control in my visual webpart. I need to upload the file browsed, when i click save button to the field of type 'Image' in a custom list.
    – Suja Shyam
    Commented Sep 4, 2012 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.