Friday, April 10, 2009

Object reference not set to an instance of an object for File Text Box

I was programming an image uploading function by using File Text Box recently in ASP.NET with AJAX and happen to bump into this error below when I try to submit my file path:


I actually reused the code that I've did for another system in ASP.NET 1.0 and even tested again in the system and it works perfectly, but it just doesn't want to run in ASP.NET 2.0. Spending the entire night of pondering the cause of this, still no go until one of my Indonesian friends told me that the cause of this problem was actually from AJAX's Update Panel. O.o

What happen was I actually have a Label in an Update Panel which I used for error checking just in case the user posting incomplete information for file uploads, until now I have no idea how does the Update Panel react to the File Text Box and produce such error, but it works perfectly after I remove the Update Panel tag, which left the Label alone in the page.

In case you wanna know how File Text Box works, below are some of the useful codes:

HTML File Text Box Control:
<input id="Filetextbox1" style="WIDTH: 216px; HEIGHT: 22px" type="file" size="16" name="Filetextbox1" runat="server">

VB.NET Import Class/Library:
Imports System.IO

VB.NET Button Click Action:
If Page.IsPostBack Then
Dim filetextboxPath As String = Filetextbox1.PostedFile.FileName
Dim i As Integer = InStr(1, StrReverse(filetextboxPath), "\")
Dim fileName As String = Mid(filetextboxPath, (Len(filetextboxPath) - i) + 2)
Dim file As String
file = "http://localhost/freestyler/image/products/" + fileName
Filetextbox1.PostedFile.SaveAs(Server.MapPath("image/products/" + fileName))
Session("file") = file
End If

By doing so, you may insert the Session("file") into your DB as the image path :)

2 comments:

  1. William say take out Ajax..... hahahah
    nice one laaaa...
    lucky he do in his DM

    ReplyDelete