Wrox Programmer Forums
Go Back   Wrox Programmer Forums > ASP.NET and ASP > ASP.NET 4 > BOOK: Beginning ASP.NET 4 : in C# and VB
|
BOOK: Beginning ASP.NET 4 : in C# and VB
This is the forum to discuss the Wrox book Beginning ASP.NET 4: in C# and VB by Imar Spaanjaars; ISBN: 9780470502211
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning ASP.NET 4 : in C# and VB section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 15th, 2013, 12:48 PM
Friend of Wrox
 
Join Date: Apr 2013
Posts: 101
Thanks: 14
Thanked 0 Times in 0 Posts
Default Chapter 14 Inserting and Deleting Data with the ListView Control

After I enter the description, ToolTip and choose a file, when I click insert on the ManagePhotoAlbum, nothing happens. I am not getting any error but the data about the picture is not displayed on the page.

Here is my aspx code
<%@ Page Title="Manage Photo Album" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="ManagePhotoAlbum.aspx.vb" Inherits="_ManagePhotoAlbum" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id"
DataSourceID="EntityDataSource1" InsertItemPosition="LastItem">
<InsertItemTemplate>
<li style="">
Description:
<asp:RequiredFieldValidator ID="reqDesc" ControlToValidate="DescriptionTextBox" runat="server" ErrorMessage="Enter a description." />
<asp:TextBox ID="DescriptionTextBox" runat="server"
Text='<%# Bind("Description") %>' /><br />
ToolTip:
<asp:RegularExpressionValidator ID="reqToolTip" ControlToValidate="ToolTipTextBox" runat="server" ErrorMessage="Enter a tool tip." />
<asp:TextBox ID="ToolTipTextBox" runat="server" Text='<%# Bind("ToolTip") %>' /><br />
<%--ImageUrl:
<asp:TextBox ID="ImageUrlTextBox" runat="server"
Text='<%# Bind("ImageUrl") %>' />--%>
<asp:FileUpload ID="FileUPload1" runat="server" /> <br />
<asp:CustomValidator ID="cusValImage" runat="server" ErrorMessage="Select a .jpg file." />
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" CausesValidation="False" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li style="">
Description:
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>' /><br />
ToolTip:
<asp:Label ID="ToolTipLabel" runat="server" Text='<%# Eval("ToolTip") %>' /><br />
<%--ImageUrl:
<asp:Label ID="ImageUrlLabel" runat="server" Text='<%# Eval("ImageUrl") %>' /><br />--%>
<asp:Image ID="ImageUrl" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete"
Text="Delete" CausesValidation="False" />
</li>
</ItemTemplate>
<LayoutTemplate>
<ul class="ItemContainer">
<li runat="server" id="itemPlaceholder" />
</ul>
</LayoutTemplate>
</asp:ListView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server"
ConnectionString="name=TesterEntities"
DefaultContainerName="PlanetWroxEntities" EnableDelete="True"
EnableFlattening="False" EnableInsert="True" EntitySetName="Pictures"
Where="it.PhotoAlbum.Id = @photoAlbumId">
<WhereParameters>
<asp:QueryStringParameter Name="PhotoAlbumId" QueryStringField="PhotoAlbumId"
Type="Int32" />
</WhereParameters>
</asp:EntityDataSource>
</asp:Content>

My code behind

Imports TesterModel

Partial Class _ManagePhotoAlbum
Inherits BasePage

Protected Sub EntityDataSource1_Inserting(sender As Object, e As System.Web.UI.WebControls.EntityDataSourceChanging EventArgs) Handles EntityDataSource1.Inserting
Dim photoAlbumId As Integer =
Convert.ToInt32(Request.QueryString.Get("PhotoAlbu mId"))
Dim myPicture As Picture = CType(e.Entity, Picture)
myPicture.PhotoAlbumId = photoAlbumId
'The code below saves file to disk and then updates the ImageUrl property of the Picture instance with its new location
Dim FileUpload1 As FileUpload =
CType(ListView1.InsertItem.FindControl("FileUpload 1"), FileUpload)
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(physical Folder, fileName + extension))
myPicture.ImageUrl = virtualFolder + fileName + extension
End Sub

Protected Sub ListView1_ItemInserting(sender As Object, e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles ListView1.ItemInserting
Dim FileUpload1 As FileUpload = CType(ListView1.InsertItem.FindControl("FileUpload 1"), FileUpload)
If Not FileUpload1.HasFile OrElse Not FileUpload1.FileName.ToLower().EndsWith(".jpg") Then
Dim cusValImage As CustomValidator = CType(ListView1.InsertItem.FindControl("cusValImag e"), CustomValidator)
cusValImage.IsValid = False
e.Cancel = True
End If
End Sub
End Class

Last edited by winkimjr2; May 15th, 2013 at 12:59 PM..
 
Old May 15th, 2013, 02:37 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Hi there,

I compared this code with mine, and I can't see anything wrong. Does the code in the code behind fire at all? Have you tried to debug your code (discussed in Chapter 18) and see if the code is executed?

Other things to check:

1. The relationship between the two tables in the database (PhotoAlbum.Id should be linked to Picture.PhotoAlbumId).

2. The GigPics folder on disk. Does it contain the pictures?

3. The database itself. Do you see the pictures in the Picture table?

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 15th, 2013, 04:27 PM
Friend of Wrox
 
Join Date: Apr 2013
Posts: 101
Thanks: 14
Thanked 0 Times in 0 Posts
Default

1. The relationship between the two tables in the database (PhotoAlbum.Id should be linked to Picture.PhotoAlbumId).
Yes I have the link right

2. The GigPics folder on disk. Does it contain the pictures? Yes I have 3 images from your book

3. The database itself. Do you see the pictures in the Picture table?
No the picture table does not have any pictures and I am not sure how to upload them into the table.

I have not looked into chapter 18 yet so I am not sure on how to find out if the code in the code behind fire at all.
I have not tried to debug my code (discussed in Chapter 18) because I don't know how and I have not got to chapter 18.

I tried to debug but when I do not enter something in the TootTip, I get an error but when I click on insert after selecting a photo, nothing happens.

Last edited by winkimjr2; May 16th, 2013 at 09:50 AM.. Reason: Updating debugging status
 
Old May 16th, 2013, 03:54 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Can you post the full code for the 2 pages (markup and code behind)? Maybe you're not passing the correct ID to the ManageAlbum page?

Please use the code tag (the # button on this forum's toolbar) to wrap your code (after pasting and copying it from Notepad). Otherwise this forum may mess up your code.

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 16th, 2013, 12:14 PM
Friend of Wrox
 
Join Date: Apr 2013
Posts: 101
Thanks: 14
Thanked 0 Times in 0 Posts
Default

Thanks for your response. As always I appreciate your help. I have spent countless hours including asking a friend finding the problem to no avail.

Here is code for NewPhotoAlbum.aspx code
Code:
<%@ Page Title="Create New Photo Album" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="NewPhotoAlbum.aspx.vb" Inherits="_NewPhotoAlbum" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">
  <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
    DataKeyNames="Id" DataSourceID="EntityDataSource3" DefaultMode="Insert" EnableInserting="True"
    Height="50px" Width="125px">
    <Fields>
      <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" 
        SortExpression="Id" InsertVisible="False" />
      <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
      <asp:CommandField ShowInsertButton="True" />
    </Fields>
  </asp:DetailsView>
  <asp:EntityDataSource ID="EntityDataSource3" runat="server" 
    ConnectionString="name=TesterEntities" 
    DefaultContainerName="PlanetWroxEntities" EnableFlattening="False" 
    EnableInsert="True" EntitySetName="PhotoAlbums">
  </asp:EntityDataSource>
  </asp:Content>
Here is NewPhotoAlbum.aspx.vb code
Code:
Imports TesterModel
Partial Class _NewPhotoAlbum
  Inherits BasePage

  Protected Sub EntityDataSource3_Inserting(sender As Object, e As System.Web.UI.WebControls.EntityDataSourceChangingEventArgs) Handles EntityDataSource3.Inserting
    Dim myPhotoAlbum As PhotoAlbum = CType(e.Entity, PhotoAlbum)
    Response.Redirect(String.Format("ManagePhotoAlbum.aspx?PhotoAlbumId={0}", myPhotoAlbum.Id.ToString()))
  End Sub
End Class
Here is ManagePhotoAlbum aspx code
Code:
<%@ Page Title="Manage Photo Album" Language="VB" MasterPageFile="~/MasterPages/Frontend.master" AutoEventWireup="false" CodeFile="ManagePhotoAlbum.aspx.vb" Inherits="_ManagePhotoAlbum" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">
  <asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" 
    DataSourceID="EntityDataSource1" InsertItemPosition="LastItem">
    <InsertItemTemplate>
      <li style="">
        Description:
        <asp:RequiredFieldValidator ID="reqDesc" ControlToValidate="DescriptionTextBox" runat="server" ErrorMessage="Enter a description." />
        <asp:TextBox ID="DescriptionTextBox" runat="server" 
          Text='<%# Bind("Description") %>' /><br />
          ToolTip:
        <asp:RegularExpressionValidator ID="reqToolTip" ControlToValidate="ToolTipTextBox" runat="server" ErrorMessage="Enter a tool tip." />
        <asp:TextBox ID="ToolTipTextBox" runat="server" Text='<%# Bind("ToolTip") %>' /><br />
        <%--ImageUrl:
        <asp:TextBox ID="ImageUrlTextBox" runat="server" 
          Text='<%# Bind("ImageUrl") %>' />--%>
        <asp:FileUpload ID="FileUPload1" runat="server" /> <br />
        <asp:CustomValidator ID="cusValImage" runat="server" ErrorMessage="Select a .jpg file." />
        <asp:Button ID="InsertButton" runat="server" CommandName="Insert" 
          Text="Insert" />
        <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" 
          Text="Clear" CausesValidation="False" />
      </li>
    </InsertItemTemplate>
    <ItemTemplate>
      <li style="">
        Description:
        <asp:Label ID="DescriptionLabel" runat="server" 
          Text='<%# Eval("Description") %>' /><br />
        ToolTip:
        <asp:Label ID="ToolTipLabel" runat="server" Text='<%# Eval("ToolTip") %>' /><br />
        <%--ImageUrl:
        <asp:Label ID="ImageUrlLabel" runat="server" Text='<%# Eval("ImageUrl") %>' /><br />--%>
        <asp:Image ID="ImageUrl" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' /><br />
        <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" 
          Text="Delete" CausesValidation="False" />
      </li>
    </ItemTemplate>
    <LayoutTemplate>
      <ul class="ItemContainer">
        <li runat="server" id="itemPlaceholder" />
      </ul>
    </LayoutTemplate>
    </asp:ListView>
  <asp:EntityDataSource ID="EntityDataSource1" runat="server" 
    ConnectionString="name=TesterEntities" 
    DefaultContainerName="PlanetWroxEntities" EnableDelete="True" 
    EnableFlattening="False" EnableInsert="True" EntitySetName="Pictures" 
    Where="it.PhotoAlbum.Id = @photoAlbumId">
    <WhereParameters>
      <asp:QueryStringParameter Name="PhotoAlbumId" QueryStringField="PhotoAlbumId" 
        Type="Int32" />
    </WhereParameters>
  </asp:EntityDataSource>
</asp:Content>
Here is ManagePhotoAlbum.aspx.vb
Code:
Imports TesterModel

Partial Class _ManagePhotoAlbum
  Inherits BasePage

  Protected Sub EntityDataSource1_Inserting(sender As Object, e As System.Web.UI.WebControls.EntityDataSourceChangingEventArgs) Handles EntityDataSource1.Inserting
    Dim photoAlbumId As Integer =
      Convert.ToInt32(Request.QueryString.Get("PhotoAlbumId"))
    Dim myPicture As Picture = CType(e.Entity, Picture)
    myPicture.PhotoAlbumId = photoAlbumId
    'The code below saves file to disk and then updates the ImageUrl property of the Picture instance with its new location
    Dim FileUpload1 As FileUpload =
      CType(ListView1.InsertItem.FindControl("FileUpload1"), FileUpload)
    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))
    myPicture.ImageUrl = virtualFolder + fileName + extension
  End Sub

  Protected Sub ListView1_ItemInserting(sender As Object, e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles ListView1.ItemInserting
    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"
      e.Cancel = "True"
    End If
  End Sub
End Class

Last edited by winkimjr2; May 16th, 2013 at 12:33 PM..
 
Old May 17th, 2013, 03:56 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Ah, I see what the problem is now. You're hooking into the wrong event of the EntityDataSource control. Take a look at your code from NewPhotoAlbum,aspx.vb:

Code:
Protected Sub EntityDataSource3_Inserting(sender As Object, e As System.Web.UI.WebControls.EntityDataSourceChangingEventArgs) Handles EntityDataSource3.Inserting
  Dim myPhotoAlbum As PhotoAlbum = CType(e.Entity, PhotoAlbum)
  Response.Redirect(String.Format("ManagePhotoAlbum.aspx?PhotoAlbumId={0}", 
             myPhotoAlbum.Id.ToString()))
End Sub
You're executing this code on Inserting which means the new album hasn't been inserted yet, and its ID is still zero. This in turn causes the redirect to look like this:

Code:
ManagePhotoAlbum.aspx?PhotoAlbumId=0
Notice how it's passing 0 instead of the ID of the new album. This causes an error when inserting a new Picture as there is no album with an ID of 0.

You can fix it by handling the Inserted event instead:
Code:
Protected Sub EntityDataSource3_Inserted(sender As Object, e As System.Web.UI.WebControls.EntityDataSourceChangedEventArgs) Handles EntityDataSource3.Inserted
  Dim myPhotoAlbum As PhotoAlbum = CType(e.Entity, PhotoAlbum)
  Response.Redirect(String.Format("ManagePhotoAlbum.aspx?PhotoAlbumId={0}", 
               myPhotoAlbum.Id.ToString()))
End Sub
Hope this helps,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!

Last edited by Imar; May 17th, 2013 at 03:58 AM..
 
Old May 17th, 2013, 04:06 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Oh, and two more things:

1. This code in ManagePhotoAlbum.aspx:

Code:
<asp:RegularExpressionValidator ID="reqToolTip" ControlToValidate="ToolTipTextBox" runat="server" ErrorMessage="Enter a tool tip." />
will prevent the form from being submitted. I think you meant to add a RequiredFieldValidator instead.

2. VB will let you get away with it, but booleans should be expressed as booleans, not as strings. In other words, this:

Code:
cusValImage.IsValid = "False"
e.Cancel = "True"
should be this:

Code:
cusValImage.IsValid = False
e.Cancel = True
Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 17th, 2013, 09:43 AM
Friend of Wrox
 
Join Date: Apr 2013
Posts: 101
Thanks: 14
Thanked 0 Times in 0 Posts
Default

Thanks for the response.
1. I do not know how to do the handling you mentioned i.e handling the Inserted event instead
Code:
Protected Sub EntityDataSource3_Inserted(sender As Object, e As System.Web.UI.WebControls.EntityDataSourceChangedEventArgs) Handles EntityDataSource3.Inserted
  Dim myPhotoAlbum As PhotoAlbum = CType(e.Entity, PhotoAlbum)
  Response.Redirect(String.Format("ManagePhotoAlbum.aspx?PhotoAlbumId={0}", 
               myPhotoAlbum.Id.ToString()))
End Sub
2. I am now getting the following error:

Code:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Picture_PhotoAlbum". The conflict occurred in database "Tester", table "dbo.PhotoAlbum", column 'Id'.
The statement has been terminated. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Picture_PhotoAlbum". The conflict occurred in database "Tester", table "dbo.PhotoAlbum", column 'Id'.
The statement has been terminated.
 
Old May 17th, 2013, 10:05 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Quote:
I do not know how to do the handling you mentioned i.e handling the Inserted event instead
Not sure I understand. You should simply replace your code block I posted with my code.

Quote:
I am now getting the following error:
What do you see in the browser's address bar? Did you start by creating a new photo album from NewPhotoAlbum.aspx?

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old May 17th, 2013, 12:22 PM
Friend of Wrox
 
Join Date: Apr 2013
Posts: 101
Thanks: 14
Thanked 0 Times in 0 Posts
Default

Yes I did start by creating a new photo album from NewPhotoAlbum.
Here is what I see on the browser address bar
Code:
http://localhost:19074/Site/ManagePhotoAlbum.aspx?PhotoAlbumId=0





Similar Threads
Thread Thread Starter Forum Replies Last Post
Chapter 14 errors for Inserting and Deleting Data with the ListView Control winkimjr2 BOOK: Beginning ASP.NET 4 : in C# and VB 7 May 15th, 2013 02:28 PM
Chapter 14 Paging Data with the Listview and DataPager Controls rmanapul BOOK: Beginning ASP.NET 4 : in C# and VB 4 May 22nd, 2012 04:10 AM
Chapter 14 Customizing Templates of the ListView Control rmanapul BOOK: Beginning ASP.NET 4 : in C# and VB 7 May 21st, 2012 04:42 AM
Ch 14 Customizing Templates of the ListView Control leeWozyWarren BOOK: Beginning ASP.NET 4 : in C# and VB 3 December 4th, 2011 06:16 AM
Chapter 14, Listview control problem SamuelMSr BOOK: Beginning ASP.NET 4 : in C# and VB 3 September 28th, 2011 02:47 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.