03.11.2016 Views

Beginning ASP.NET 4.5 in CSharp and VB Opsylum

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

540 x CHAPTER 14 LINQ AND THE ADO.<strong>NET</strong> ENTITY FRAMEWORK<br />

str<strong>in</strong>g physicalFolder = Server.MapPath(virtualFolder);<br />

str<strong>in</strong>g fileName = Guid.NewGuid().ToStr<strong>in</strong>g();<br />

str<strong>in</strong>g extension = System.IO.Path.GetExtension(FileUpload1.FileName);<br />

FileUpload1.SaveAs(System.IO.Path.Comb<strong>in</strong>e(physicalFolder, fileName + extension));<br />

myPicture.ImageUrl = virtualFolder + fileName + extension;<br />

7. Go back to Markup View <strong>and</strong> add three validation controls to the InsertItemTemplate: two<br />

RequiredFieldValidator controls hooked up to the text boxes for the Description <strong>and</strong><br />

ToolTip, <strong>and</strong> one CustomValidator with its ErrorMessage set to Select a valid .jpg file.<br />

Give the RequiredFieldValidator controls an ID such as reqDesc <strong>and</strong> reqToolTip <strong>and</strong> assign<br />

the CustomValidator an ID of cusValImage. F<strong>in</strong>ally, set the TextMode property of the text box<br />

for the Description to MultiL<strong>in</strong>e <strong>and</strong> enter a l<strong>in</strong>e break (a ) before the Insert button.<br />

You should end up with the follow<strong>in</strong>g code:<br />

Description:<br />

<br />

<br />

ToolTip:<br />

<br />

<br />

<br />

<br />

<br />

<br />

8. Select the ListView control <strong>in</strong> Design View <strong>and</strong> set up an event h<strong>and</strong>ler for its ItemInsert<strong>in</strong>g<br />

event by double-click<strong>in</strong>g the event <strong>in</strong> the Events tab of the Properties Grid. Complete the event h<strong>and</strong>ler<br />

with the follow<strong>in</strong>g code:<br />

<strong>VB</strong>.<strong>NET</strong><br />

Protected Sub ListView1_ItemInsert<strong>in</strong>g(sender As Object,<br />

e As ListViewInsertEventArgs) H<strong>and</strong>les ListView1.ItemInsert<strong>in</strong>g<br />

Dim FileUpload1 As FileUpload =<br />

CType(ListView1.InsertItem.F<strong>in</strong>dControl("FileUpload1"), FileUpload)<br />

If Not FileUpload1.HasFile OrElse<br />

Not FileUpload1.FileName.ToLower().EndsWith(".jpg") Then<br />

Dim cusValImage As CustomValidator =<br />

CType(ListView1.InsertItem.F<strong>in</strong>dControl("cusValImage"), CustomValidator)<br />

cusValImage.IsValid = False<br />

e.Cancel = True<br />

End If<br />

End Sub<br />

C#<br />

protected void ListView1_ItemInsert<strong>in</strong>g(object sender, ListViewInsertEventArgs e)<br />

{<br />

FileUpload FileUpload1 =

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!