...

View Full Version : Adding an ELSE clause somewhere



Max01
02-27-2007, 12:19 PM
Hi everyone,

Quick query if I may. Whilst I got to the bottom of a problem last week, thanks to this forum, another one has reared its ugly head; and it is as follows.

I have an online form which allows users to upload a photo, however, if a user attempts to submit the form without uploading a photo, ASP.NET throws an exception. Question, how can I modify the following code so as to avoid an exception. I have a feeling I need to incorporate an ELSE clause somehere.

Protected Sub frmPhoto_ItemInserting(ByVal sender As Object, ByVal e As FormViewInsertEventArgs)
' Get the FileUpload control
Dim upPhoto As FileUpload = CType(frmInsert.FindControl("upPhoto"), FileUpload)
srcEmployee.InsertParameters("FileName").DefaultValue = upPhoto.FileName

' Save contents to file system
Dim savePath As String = MapPath("~/Photos/" + upPhoto.FileName)
upPhoto.SaveAs(savePath)
End Sub

nikkiH
02-27-2007, 02:35 PM
Just use a validator. They're good for that.


<asp:RequiredFieldValidator runat="server" id="fileUploadControlRequired"
ErrorMessage="You didn't choose a file to upload. Please choose a file that is on your computer, then try again."
ControlToValidate="fileUploadControl"
Display="Dynamic" />

Max01
02-27-2007, 02:49 PM
Thanks. I've used vaildators qute extensively for the important textboxes, however I shouldn't expect users to have images on hand; that's why it cannot be enforced by a validation property. Do you not think an 'if else' will do?

otaku149
02-27-2007, 03:18 PM
[ASP.Net 2.0]

Use the HasFile property to make sure the user had selected a file to upload:



If upPhoto.HasFile Then
'code here
upPhoto.SaveAs(savePath)
End If

nikkiH
02-27-2007, 04:30 PM
Thanks. I've used vaildators qute extensively for the important textboxes, however I shouldn't expect users to have images on hand; that's why it cannot be enforced by a validation property. Do you not think an 'if else' will do?

Sure, if it isn't actually required.
See otaku149's solution.

Max01
02-27-2007, 06:06 PM
I very much appreciate both of your comments; thanks. The code works perfectly and was inserted as follows:

Protected Sub frmPhoto_ItemInserting(ByVal sender As Object, ByVal e As FormViewInsertEventArgs)

' Get the FileUpload control
Dim upPhoto As FileUpload = CType(frmInsert.FindControl("upPhoto"), FileUpload)
If upPhoto.HasFile Then
srcEmployee.InsertParameters("FileName").DefaultValue = upPhoto.FileName

' Save contents to file system
Dim savePath As String = MapPath("~/Photos/" + upPhoto.FileName)
upPhoto.SaveAs(savePath)

End If
End Sub



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum