1

在引用 ListViewInsertEventArgs 的 e.Values 方法时,我可以使用 linq 和 listview 控件将图像上传到数据库,但是 ListViewEditEventArgs 中没有这样的方法,那么我可以使用什么来实现相同的结果?

这是我的插入代码:

protected void ProjectPhotosList_ItemInserting(对象发送者,ListViewInsertEventArgs e)

{

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

标签 fileuploadlbl = (标签)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";
    }
}
4

1 回答 1

0

好的,我已经解决了这个问题!我只需要采取一些不同的方式:

这是重要的代码:

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

它只是获取所选行的主键值的简单方法。我找到了一篇关于将 pdf 上传到数据库的帖子,并决定以此为基础编写我的其余代码。所以这里是完整的代码:

protected void ProjectPhotosList_ItemUpdating(对象发送者,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();
    }
于 2008-10-30T17:55:53.083 回答