I have followed the book but when I try to add a photo by clicking the insert button. I get an error on the underlined line of code. How can I fix this?
the error I get:
An exception of type 'System.NullReferenceException' occurred in App_Web_fc2yp5zf.dll but was not handled in user code
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=App_Web_fc2yp5zf
StackTrace:
at _ManagePhotoAlbum.ListView1_InsertItem(Int32 photoAlbumId) in C:\BegASPNET\PlanetWrox\ManagePhotoAlbum.aspx.
vb:l ine 19
InnerException:
Code:
Imports System.Web.ModelBinding
Partial Class _ManagePhotoAlbum
Inherits BasePage
Public Function ListView1_GetData(<QueryString("PhotoAlbumId")> photoAlbumId As Integer) As IQueryable
Dim myEntities As New PlanetWroxEntities()
Return From p In myEntities.Pictures
Where p.PhotoAlbumId = photoAlbumId
Select p
End Function
Public Sub ListView1_InsertItem(<QueryString("PhotoAlbumId")> photoAlbumId As Integer)
Dim picture As New Picture()
TryUpdateModel(picture)
Dim FileUpload1 As FileUpload = CType(ListView1.InsertItem.FindControl("FileUpload1"), FileUpload)
If Not FileUpload1.HasFile OrElse Not FileUpload1.FileName.ToLower().EndsWith(".jpg") Then
Dim cusValImage As CustomValidator = CType(ListView1.InsertItem.FindControl("cusValImage"), CustomValidator)
cusValImage.IsValid = False
ModelState.AddModelError("Invalid file type", cusValImage.ErrorMessage)
End If
If ModelState.IsValid AndAlso Page.IsValid Then
Using myEntities As New PlanetWroxEntities()
picture.PhotoAlbumId = photoAlbumId
Dim virtualFolder As String = "~/GigPics/"
Dim physicalFolder As String = Server.MapPath(virtualFolder)
Dim fileName As String = Guid.NewGuid().ToString()
Dim extension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
FileUpload1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension))
picture.ImageUrl = virtualFolder + fileName + extension
myEntities.Pictures.Add(picture)
myEntities.SaveChanges()
End Using
End If
End Sub
Public Sub ListView1_DeleteItem(ByVal id As Integer)
Using myEntities As New PlanetWroxEntities()
Dim picture = (From p In myEntities.Pictures
Where p.Id = id
Select p).Single()
myEntities.Pictures.Remove(picture)
myEntities.SaveChanges()
End Using
End Sub
End Class
Found what was wrong. I forgot to change the ID in step 3.