Shining Star Services LLC
C# and VB Project: A Tutorial Using Data Sets, Table Adapters, WebForms, Controls, File Upload, Excel Import
Section 3: FileUpload Control and Functionality
by Nannette Thacker

In this section of our tutorial, we are going to look at the "FileUpload" control. We will discuss how to set a Label text value and set Panel visibility from Codebehind. We will also learn how to use the Handles key word at the end of our procedure declarations to handle our Button Click events.

Our "Excel Spreadsheet File Upload" button will activate our FileUpload control. The FileUpload control allows the user to select a "Browse" button to find the file on their hard drive. The user may then select the "Upload File" button in order to upload the file to the web server. We will learn how to create a function to save an uploaded file in our Codebehind.

WebForm FileUpload Control

In our "PanelUpload" Panel, add a "FileUpload" control with the ID "FileUploadExcel." Next, add text instructions for the user to "Please select an Excel file to import:" and add a "ButtonUploadFile" Button control. Let's also add a Label with ID "LabelUpload" with no text. We'll use this to display our file upload results.

<asp:Panel ID="PanelUpload" runat="server" Visible="False">
    <asp:FileUpload ID="FileUploadExcel" runat="server" />
    <br />
    Please select an Excel file to import:<br />
    <asp:Button ID="ButtonUploadFile" runat="server" 
        Text="Upload File" /><br />
    <asp:Label ID="LabelUpload" runat="server" Text=""></asp:Label>
</asp:Panel>
Upload Excel Spreadsheet Functionality

In our codebehind page, we will add a ButtonUpload_Click Protected Sub procedure to our page class. Notice the Handles key word used at the end of the procedure declaration. Please see my article on OnClick and Handles Caution for further details about using the Handles key word in VB.


VB:

Protected Sub ButtonUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles ButtonUpload.Click
PanelUpload.Visible =
True
PanelView.Visible = False
PanelImport.Visible = False
End Sub




In our C# version, our code in front defines the click event with the button. You may also do it this way in VB:

<asp:Button ID="ButtonUpload" runat="server" 
                    Text="Upload Excel Spreadsheet" OnClick="ButtonUpload_Click" />
                    Text="Uplad Excel Spreadsheet" OnClick="ButtonUpload_Click" />
     
C#

protected void ButtonUpload_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible =
true;
PanelView.Visible =
false;
PanelImport.Visible =
false;
}


Now we need to add a Sub procedure for when the user clicks the Upload File button. Our new ButtonUploadFile_Click Sub will handle the ButtonUploadFile.Click. In the below code, notice that we use "FileUploadExcel.HasFile" to check and see if a file was selected before the "Upload File" button was depressed.

We then save the file to the hard drive. We set our Label text to include the "PostedFile.FileName" and "PostedFile.ContentType" and size of the file using "PostedFile.ContentLength."

For error detection, notice we use Try/Catch to check for Exceptions. If there is an error, the error message is displayed in the Label.

VB:

Protected Sub ButtonUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles ButtonUploadFile.Click

        If FileUploadExcel.HasFile Then
            Try
                ' alter path for your project
                FileUploadExcel.SaveAs(Server.MapPath("~/ExcelImport.xls"))

                LabelUpload.Text = "Upload File Name: " & _
                     FileUploadExcel.PostedFile.FileName & "<br>" & _
                     "Type: " & _
                     FileUploadExcel.PostedFile.ContentType & _
                     " File Size: " & _
                     FileUploadExcel.PostedFile.ContentLength & " kb<br>"
            Catch ex As Exception
                LabelUpload.Text = "Error: " & ex.Message.ToString
            End Try
        Else
            LabelUpload.Text = "Please select a file to upload."
        End If

    End Sub
Please see this article from the Microsoft library for more information on the Try/Catch/Finally Statement.

C#

    protected void ButtonUploadFile_Click(object sender, System.EventArgs e)
    {

        if (FileUploadExcel.HasFile)
        {


            try
            {
                // alter path for your project
                
                FileUploadExcel.SaveAs(Server.MapPath("~/ExcelImport.xls"));
                LabelUpload.Text = "Upload File Name: " + 
                FileUploadExcel.PostedFile.FileName + 
                "<br>" + "Type: " + 
                FileUploadExcel.PostedFile.ContentType + 
                " File Size: " + FileUploadExcel.PostedFile.ContentLength 
                + " kb<br>";
            }
            catch (System.NullReferenceException ex) 
            {
                LabelUpload.Text = "Error: " + ex.Message;
            }
        }
        else
        {
            LabelUpload.Text = "Please select a file to upload.";
        }

    }
Let's continue with Section 4: Auto Formatting a Web Form GridView.

May your dreams be in ASP.NET!

Nannette Thacker

C# and VB Project: Importing an Excel Spreadsheet to a Database Using Data Sets and Table Adapters:

Introduction: C# and VB Project: A Tutorial Using Data Sets, Table Adapters, WebForms, Controls, File Upload, Excel Import
Section 1: Creating Our Project, Database and Tables
Section 2: WebForm: Table, Label, and Panel Controls
Section 3: FileUpload Control and Functionality
Section 4: Auto Formatting a Web Form GridView
Section 5: Bind the Excel Data to a GridView using an OleDbDataAdapter
Section 6: Data Access Layer DataSet TableAdapters
Section 7: TableAdapter Select and Insert Queries with Parameters
Section 8: Using an OleDbDataReader to Retrieve Our Data
Section 9: Using our TableAdapters, DataTables and Intellisense

Download the ZIP files:

C#: ShiningStarCExcel.zip
VB: ShiningStarVBExcel.zip

About the Author

Nannette Thacker is an ASP.NET web application developer and SQL Server developer. She is owner of the ASP.NET consulting firm, Shining Star Services, LLC in Kansas City. Nannette specializes in ASP Classic to ASP.NET conversions and custom Membership Provider solutions as well as existing or new ASP.NET development. Nannette's many articles on ASP.NET, ASP Classic, Javascript and more may be read at http://www.shiningstar.net. You may also view her http://weblogs.asp.net/nannettethacker/ web blog.

© Copyright 1997-2017 Shining Star Services LLC, Nannette Thacker. All Rights Reserved.