views:

391

answers:

1

Hi, i can upload images to the database using linq and the listview control when referancing the e.Values method for the ListViewInsertEventArgs, but there is no such method in the ListViewEditEventArgs, so what can i use to achieve the same results?

here is my inserting code:

protected void ProjectPhotosList_ItemInserting(object sender, ListViewInsertEventArgs e)

{

FileUpload uplImage = (FileUpload)ProjectPhotosList.InsertItem.FindControl("uplImage");

Label fileuploadlbl = (Label)ProjectPhotosList.InsertItem.FindControl("fileuploadlbl");

    byte[] img = null;
    if (uplImage.HasFile || !uplImage.FileName.ToLower().EndsWith(".jpg"))
    {
        try
        {
            img = new byte[uplImage.PostedFile.ContentLength];
            uplImage.PostedFile.InputStream.Read(img, 0, img.Length);
        }
        catch
        {
            fileuploadlbl.Text = "unable to upload " + uplImage.FileName.ToString();
        }
    }
    if (img == null)
    {
        e.Cancel = true;
        fileuploadlbl.Text = "Please choose a file to upload";
    }

    try
    {
        e.Values.Add("ProjectPhoto", new System.Data.Linq.Binary(img));
        fileuploadlbl.Text = "File Upload Successful";
    }
    catch
    {
        fileuploadlbl.Text = "File Upload Failed, please try again";
    }
}
A: 

ok so i have solved the issue! I just had to go about it a bit of a different way:

this is the important code:

int mykey = int.Parse(ProjectPhotosList.DataKeys[e.ItemIndex].Value.ToString());

its just a simple way to get the primarykey value of the selected row. I found a post about uploading pdf's to a database and decided to base the rest of my code on that. So here the full code:

protected void ProjectPhotosList_ItemUpdating(object sender, ListViewUpdateEventArgs e)

{

FileUpload myFile = (FileUpload)ProjectPhotosList.EditItem.FindControl("uploadImage");

    TextBox myCaption = (TextBox)ProjectPhotosList.EditItem.FindControl("ProjectPhotoCaptionTextBox");

    int mykey = int.Parse(ProjectPhotosList.DataKeys[e.ItemIndex].Value.ToString());

    if (myFile.HasFile)
    {

        //Get the posted file
        Stream fileDataStream = myFile.PostedFile.InputStream;

        //Get length of file
        int fileLength = myFile.PostedFile.ContentLength;

        //Create a byte array with file length
        byte[] fileData = new byte[fileLength];

        //Read the stream into the byte array
        fileDataStream.Read(fileData, 0, fileLength);

        //get the file type
        string fileType = myFile.PostedFile.ContentType;

        //Open Connection
        PHJamesDataContext db = new PHJamesDataContext();
        //Find the Right Row
        PHJProjectPhoto Newphoto = (from p in db.PHJProjectPhotos
                                    where p.ProjectPhotoId == mykey
                                    select p).Single<PHJProjectPhoto>();


        Newphoto.ProjectPhoto = fileData;

        db.SubmitChanges();
    }
Joe