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.

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

  • 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 Sep 4 '12 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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