0

I am trying to move an UploadFile function to a BasePage so that I can re-use it on many aspx pages. My original code is as follows:

upload.aspx.cs

public partial class upload : CodeBasePage
{

protected void uploadFile_Click(object sender, EventArgs e)
{
   if (UploadImages.HasFiles)
   { 
   try
   {
     foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
     { 
     //Upload stuff;
     }
   ...

upload.aspx

<asp:FileUpload runat="server" ID="UploadImages" />
<asp:Button runat="server" ID="uploadedFile" Text="Upload" OnClick="uploadFile_Click"/>

So far so good. The code works fine.

Now I want to move the uploadFile_Click to the BasePage (CodeBasePage) so that I can re-use it on many aspx pages.

I moved the following to the CodeBasePage and declared the variables:

CodeBasePage.cs

public Button uploadedFile;
public FileUpload UploadImages;

protected void uploadFile_Click(object sender, EventArgs e)
{
   if (UploadImages.HasFiles)
   { 
   try
   {
     foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
     { 
     //Upload stuff;
     }
   ...

But apparently I'm doing something wrong. When I click the Upload button on the aspx page I get the error that "Object reference not set to an instance of an object".

Line 292:            if (UploadImages.HasFiles)

Any advice would be appreciated. I think the problem lies in how to send the upload variables from the upload.aspx page to the CodeBasePage.cs.

Gloria
  • 1,305
  • 5
  • 22
  • 57

1 Answers1

0

So you are missing a concrete FileUpload instance in your CodeBasePage class.

What you have

public FileUpload UploadImages

is only a reference. You should set it to a concrete instance either in the constructor or later by hand.

For the upload.aspx page your concrete instance is

<asp:FileUpload runat="server" ID="UploadImages" />
Recep Karabıçak
  • 2,083
  • 1
  • 18
  • 20
  • Any more details/links on how to accomplish that... I'm still in a learning process! – Gloria Nov 18 '14 at 11:19
  • 1
    For this particular control i would create a reusable user control instead of adding it to a base page you can find more detail in this [article](http://msdn.microsoft.com/en-us/library/3457w616%28v=vs.90%29.aspx). In order to get an idea what goes into a base page there are many articles you can find with a simple google search. (A late reply but i hope it helps) – Recep Karabıçak Nov 19 '14 at 20:37
  • In fact I got the same idea that using a User Control is the best option for this case. Thank you for the tip anyway. – Gloria Nov 20 '14 at 07:11