Friday, June 29, 2012

Uploading Files in ASP.NET 2.0

 
252 out of 370 rated this helpful - Rate this topic
Bill Evjen
Reuters
December 2005
Applies to:
Microsoft ASP.NET 2.0
Microsoft Visual Web Developer 2005 Express Edition

Summary: Learn how to use the new FileUpload server control in Microsoft ASP.NET 2.0. (18 printed pages)

Contents

Introduction
An Example of the FileUpload Server Control
Conclusion

Introduction

Ever since Microsoft ASP.NET was introduced with version 1.0, there has been the built-in means of building Web applications that had the ability to upload files to the hosting server. This was done through the use of the File Field HTML server control. I previously wrote an MSDN article on how to effectively use this control in your ASP.NET applications. This article is a reintroduction to the file upload process, but instead of using the File Field control, I will show you how to effectively use the new FileUpload server control that is offered through ASP.NET 2.0.
It is important to note that while this article introduces you to the new FileUpload server control, it is still quite possible to use the File Field control in your applications today.

An Example of the FileUpload Server Control

When using the File Field control in ASP.NET 1.x you had to take a few extra steps to get everything in line and working. For example, you were required to add enctype="multipart/form-data" to the page's
element on your own. The new FileUpload server control provided in ASP.NET 2.0 makes the process of uploading files to the hosting server as simple as possible.
In the end, you are trying to allow access to program the HTML tag. This tag is used to work with file data within an HTML form. In the past when using classic ASP (ASP 3.0 or earlier), many programmers worked with third-party components to upload files from the client to the server. Now, with .NET and this new control, uploading is taken care of for you. Listing 1 shows you how to use the FileUpload control to upload files to the server.
Note The sample code is provided in both Microsoft Visual Basic and C#.
Listing 1. Uploading files to the server using the FileUpload control
Visual Basic






    Upload Files


    
 
C#






    Upload Files


    
 
Running this page, you will notice a few things if you look at the source code generated for the page. This source code is presented in Listing 2.
Listing 2. The source code generated from the FileUpload control

   Upload Files


    
 
The first thing to notice is that because the FileUpload control is on the page, ASP.NET 2.0 modified the page's
element on your behalf by adding the appropriate enctype attribute. You will also notice that the FileUpload control was converted to an HTML element.
When the page from Listing 1 is run, you can select a file and upload it to the server by clicking the Upload File button on the page. There are some important items we should go over for this example so you understand all the needed pieces to make this work. For the example in Listing 1 to work, you have to make the destination folder on the server writeable for the account used by ASP.NET so the file can be saved to the specified folder.
If you think your ASP.NET account is not enabled to write to the folder you want, simply open up Microsoft Windows Explorer and navigate to the folder to which you want to add this permission. Right-click on the folder (in this case, the Uploads folder), and then select Properties. In the Properties dialog box, click on the Security tab and make sure the ASP.NET Machine Account is included in the list and has the proper permissions to write to disk (see Figure 1).
Aa479405.uploadasp201(en-us,MSDN.10).gif
Figure 1. Looking at the Security tab of the Uploads folder
If you don't see the ASP.NET Machine Account under the Security tab, you can add it by clicking the Add button and entering ASPNET (without the period) in the text area, as illustrated in Figure 2.
Aa479405.uploadasp202(en-us,MSDN.10).gif
Figure 2. Adding the ASP.NET Machine Account to the folder security definition
Click OK to add the ASP.NET Machine Account to the list. From here, make sure you give this account the proper permissions and then click OK, and you are ready to go.
The Submit button on the page causes the Button1_Click event to occur. This event uploads the file and then displays a message telling you if the upload was successful by posting information about the file uploaded. If it was unsuccessful, the page displays an error message describing why the upload failed.
By using the FileUpload control that converts itself to an tag, the browser automatically places a Browse button next to the text field on the ASP.NET page. You don't have to program anything else for this to occur. When the end user clicks the Browse button, he can navigate through the local file system to find the file to be uploaded to the server. This is shown in Figure 3. Clicking Open will place that filename and the file's path within the text field.
Aa479405.uploadasp203(en-us,MSDN.10).gif
Figure 3. Choosing a file

Working Around File Size Limitations

You may not realize it, but there is a limit to the size of a file that can be uploaded using this technique. By default, the maximum size of a file to be uploaded to the server using the FileUpload control is around 4MB. You cannot upload anything that is larger than this limit.
One of the great things about .NET, however, is that it usually provides a way around limitations. You can usually change the default settings that are in place. To change this size limit, you make some changes in either the web.config.comments (found in the ASP.NET 2.0 configuration folder at C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG) or your application's web.config file.
In the web.config.comments file, find a node called that looks like the following:
A lot is going on in this single node, but the setting that takes care of the size of the files to be uploaded is the maxRequestLength attribute. By default, this is set to 4096 kilobytes (KB). Simply change this value to increase the size of the files that you can upload to the server. If you want to allow 10 megabyte (MB) files to be uploaded to the server, set the maxRequestLength value to 11264, meaning that the application allows files that are up to 11000 KB to be uploaded to the server.
Making this change in the web.config.comments file applies this setting to all the applications that are on the server. If you want to apply this to only the application you are working with, apply this node to the web.config file of your application, overriding any setting that is in the web.config.comments file. Make sure this node resides between the nodes in the configuration file.
Another setting involved in the size limitation of files to be uploaded is the value given to the executionTimeout attribute in the node.
The value given the executionTimeout attribute is the number of seconds the upload is allowed to occur before being shut down by ASP.NET. If you are going to allow large files to be uploaded to the server, you are also going to want to increase this value along with the maxRequestLength value.
One negative with increasing the size of a file that can be uploaded is that there are hackers out there who attack servers by throwing a large number of requests at them. To guard against this, you can actually decrease the size of the files that are allowed to be uploaded; otherwise, you may find hundreds or even thousands of 10 MB requests hitting your server.

Client-Side Validation of File Types Permissible to Upload

There are several methods you can use to control the types of files that are uploaded to the server. Unfortunately, there is no bullet-proof method to protect you from someone uploading files that would be considered malicious. You can take a few steps, however, to make this process of allowing end users to upload files a little more manageable.
One nice method you can employ is to use the ASP.NET validation controls that are provided for free with ASP.NET. These controls enable you to do a regular-expression check upon the file that is being uploaded to see if the extension of the file is one you permit to be uploaded.
This is ideal for browsers that allow client-side use of the validation controls because it forces the checking to be done on the client; the file is not uploaded to the server if the signature isn't one you allow. Listing 3 shows you an example of using validation controls to accomplish this task.
Note The use of validation controls is not explained here. Take a look at Validating ASP.NET Server Controls for a complete explanation of validation controls and how to use them in your ASP.NET pages.
Listing 3. Using validation controls to restrict the types of files uploaded to the server




 









This simple ASP.NET page uses validation controls so that the end user can only upload .mp3, .mpeg, or .m3u files to the server. If the file type is not one these three choices, a Validation control throws an exception onto the screen. This is shown in Figure 4.
Aa479405.uploadasp204(en-us,MSDN.10).gif
Figure 4. Validating the file type using validation controls
Using Validation controls is not a foolproof way of controlling the files that are uploaded to the server. It wouldn't be too hard for someone to change the file extension of a file so it would be accepted and uploaded to the server, thereby bypassing this simple security model.

Adding Server-Side File Type Validation

You just saw an easy way to add some ASP.NET validation server controls to your ASP.NET page to perform a client side validation of the file extension (in just a textual manner). Now let's take a look at how to perform a similar operation on the server-side. This is presented in Listing 4.
Listing 4. Checking the file type on the server
Visual Basic
    Protected Sub Button1_Click(ByVal sender As Object, _
      ByVal e As System.EventArgs)
        If FileUpload1.HasFile Then
            Dim fileExt As String
            fileExt = System.IO.Path.GetExtension(FileUpload1.FileName)
            
            If (fileExt = ".mp3") Then
                Try
                    FileUpload1.SaveAs("C:\Uploads\" & _
                       FileUpload1.FileName)
                    Label1.Text = "File name: " & _
                      FileUpload1.PostedFile.FileName & "
" & _
                      "File Size: " & _
                      FileUpload1.PostedFile.ContentLength & " kb
" & _
                      "Content type: " & _
                      FileUpload1.PostedFile.ContentType
                Catch ex As Exception
                    Label1.Text = "ERROR: " & ex.Message.ToString()
                End Try
            Else
                Label1.Text = "Only .mp3 files allowed!"
            End If
        Else
            Label1.Text = "You have not specified a file."
        End If
    End Sub

C#
    protected void Button1_Click(object sender, EventArgs e)
    {

        if (FileUpload1.HasFile)
        {
            string fileExt = 
               System.IO.Path.GetExtension(FileUpload1.FileName);

            if (fileExt == ".mp3")
            {
                try
                {
                    FileUpload1.SaveAs("C:\\Uploads\\" + 
                       FileUpload1.FileName);
                    Label1.Text = "File name: " +
                        FileUpload1.PostedFile.FileName + "
" +
                        FileUpload1.PostedFile.ContentLength + " kb
" +
                        "Content type: " +
                        FileUpload1.PostedFile.ContentType;
                }
                catch (Exception ex)
                {
                    Label1.Text = "ERROR: " + ex.Message.ToString();
                }
            }
            else
            {
                Label1.Text = "Only .mp3 files allowed!";
            }
        }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }

Now, by using the GetExtension method from the System.IO.Path namespace, you can perform basically the same operation. It is important to note that this doesn't get around an end user's ability to simply change the file extension to something that works and upload that altered file to the hosting server.

Uploading Multiple Files at the Same Time

So far, you have seen some good examples of how to upload a file to the server without much hassle. Now let's take a look at how to upload multiple files to the server from a single page.
No built-in capabilities in the Microsoft .NET Framework enable you to upload multiple files from a single ASP.NET page. With a little work, however, you can easily accomplish this task just as you would have in the past using .NET 1.x.
The trick is to import the System.IO class into your ASP.NET page, and to then use the HttpFileCollection class to capture all the files that are sent in with the Request object. This approach enables you to upload as many files as you want from a single page.
If you wanted to, you could simply handle each and every FileUpload control on the page individually, as presented in Listing 5.
Listing 5. Handling each FileUpload control individually
Visual Basic
If FileUpload1.HasFile Then
   ' Handle file
End If

If FileUpload2.HasFile Then
   ' Handle file
End If

C#
if (FileUpload1.HasFile) {
   // Handle file
}

if (FileUpload2.HasFile) {
   // Handle file
}

This approach works, but there may be instances where you are going to want to handle the files using the HttpFileCollection class instead—especially if you are working with a dynamically generated list of server controls.
For an example of this, you can build an ASP.NET page that has three FileUpload controls and one Submit button (using the Button control). After the user clicks the Submit button and the files are posted to the server, the code behind takes the files and saves them to a specific location on the server. After the files are saved, the file information that was posted is displayed in the ASP.NET page (see Listing 6).
Listing 6. Uploading multiple files to the server
Visual Basic
Protected Sub Button1_Click(ByVal sender As Object, _
   ByVal e As System.EventArgs)

   Dim filepath As String = "C:\Uploads"
   Dim uploadedFiles As HttpFileCollection = Request.Files
   Dim i As Integer = 0

   Do Until i = uploadedFiles.Count
     Dim userPostedFile As HttpPostedFile = uploadedFiles(i)

     Try
        If (userPostedFile.ContentLength > 0) Then
           Label1.Text += "File #" & (i + 1) & "
"
           Label1.Text += "File Content Type: " & _
              userPostedFile.ContentType & "
"
           Label1.Text += "File Size: " & _
              userPostedFile.ContentLength & "kb
"
           Label1.Text += "File Name: " & _
              userPostedFile.FileName & "
"

           userPostedFile.SaveAs(filepath & "\" & _
              System.IO.Path.GetFileName(userPostedFile.FileName))

           Label1.Text += "Location where saved: " & _
              filepath & "\" & _
              System.IO.Path.GetFileName(userPostedFile.FileName) & _
              ""
        End If
     Catch ex As Exception
        Label1.Text += "Error:
" & ex.Message
     End Try
     i += 1
   Loop
End Sub

C#
protected void Button1_Click(object sender, EventArgs e)
{
   string filepath = "C:\\Uploads";
   HttpFileCollection uploadedFiles = Request.Files;
    
   for (int i = 0; i < uploadedFiles.Count; i++)
   {    
      HttpPostedFile userPostedFile = uploadedFiles[i];
    
      try
      {    
         if (userPostedFile.ContentLength > 0 )
         {
            Label1.Text += "File #" + (i+1) + 
               "
";
            Label1.Text += "File Content Type: " + 
               userPostedFile.ContentType + "
";
            Label1.Text += "File Size: " + 
               userPostedFile.ContentLength + "kb
";
            Label1.Text += "File Name: " + 
               userPostedFile.FileName + "
";
    
            userPostedFile.SaveAs(filepath + "\\" + 
               System.IO.Path.GetFileName(userPostedFile.FileName));
    
            Label1.Text += "Location where saved: " + 
               filepath + "\\" + 
               System.IO.Path.GetFileName(userPostedFile.FileName) + 
               "";
         }    
      } 
      catch (Exception Ex)
      {    
         Label1.Text += "Error: 
" + Ex.Message;    
      }    
   }    
}

The end user can select up to four files and click the Upload Files button, which initializes the Button1_Click event. Using the HttpFileCollection class with the Request.Files property lets you gain control over all the files that are uploaded from the page. When the files are in this state, you can do whatever you want with them. In this case, the files' properties are examined and written to the screen. In the end, the files are saved to the Uploads folder in the root directory of the server. The result of this action is illustrated in Figure 5.
Aa479405.uploadasp205(en-us,MSDN.10).gif
Figure 5. Uploading four files at once to the server from a single ASP.NET page
As you may have noticed, one interesting point about this example is that the states of the file input text boxes are not saved with the postback. You can see this in Figure 5. In ASP.NET, the state of the file-input text boxes cannot be saved because doing so might pose a security risk.

Conclusion

The FileUpload server control provided by ASP.NET is a powerful control that was quite difficult to achieve in the days of Active Server Pages 3.0. This new capability allows your end-users to upload one or more files to your server. Remember, you can control the size of the files that are uploaded by working with settings in either the web.config.comments or web.config file.


About the authorBill Evjen is an active proponent of .NET technologies and community-based learning initiatives for .NET. He is a technical director for Reuters, the international news and financial services company based in St. Louis, Missouri. Bill is the founder and executive director of the International .NET Association (INETA), which represents more than 100,000 members worldwide. Bill is also an author and speaker and has written such books as ASP.NET Professional Secrets, XML Web Services for ASP.NET, Web Services Enhancements, and the Visual Basic .NET Bible (all from Wiley).

GridView Examples for ASP.NET 2.0: Drilling Down into Detailed Data

In the Filtering the Data Shown in a GridView section we saw how to allow the user to display a list of products in a DropDownList and, for the selected product, list the product's order details in a GridView. That demo worked well for viewing order details for a specific product, but imagine if you wanted to put more of an emphasis on displaying product information, with viewing the order details for the products being a secondary concern. In such a situation you might want to show a GridView of the products with a way to "select" a particular GridView row. Doing so would then display the order details for the selected product in another GridView.
This common type of report is often called a drill-down report, since it shows data at one level—the list of products—with the ability to drill down into information specific to a particular product—the list of associated order details. Another common type of drill-down report is used when displaying data that has a lot of properties. For example, the Northwind database has a Customers table with numerous fields. When showing information about customers in a GridView, it might be impractical to list all of the fields of the Customers table in a GridView. Rather, it might make more sense to list only the most germane fields along with a "Details" button in each row that, when clicked, would display the particular customer's complete information.
Both of these types of drill-down reports are easily accomplished with the GridView and require no programming. In the next two sections we'll see just how easy building drill-down reports can be.

Drilling Down From One to Many

One of the many one-to-many relationships in the Northwind database can be found between the Orders or Order Details tables. The Orders table contains a record for each order placed. An order consists of one to many line items, each line item being stored as a record in the Order Details table. To illustrate a one-to-many drill-down report, let's create an ASP.NET page that lists all available orders in one GridView, where each row in this GridView has a "View Order Details" button that, when clicked, displays the particular order's line items in another GridView.
To accomplish this, start by adding a SqlDataSource to the page that retrieves all of the records from the Orders table. Next, add a GridView to the page and bind it to this SqlDataSource. In order to select an item from the GridView, check the Enable Selection link in the GridView's Smart Tag. This will add a CommandField to the GridView with a Select button.
Note The CommandField is another type of GridView column type, like the BoundField and ImageField that we examined earlier. The CommandField is used to display common command buttons, such as buttons for selection, deletion, and updating. We'll see more examples of the CommandField in the demos involving deletion and editing of the GridView's underlying data.
Next, we need a SqlDataSource that returns the right subset of order details for the selected order. To accomplish this, add another SqlDataSource to the page and configure it to select the appropriate columns from the Order Details table. Next, click the WHERE button and add a WHERE condition on the OrderID field, creating a parameter tied to the Orders GridView's SelectedValue (see Figure 29).
ms972814.gridview_fg29(en-us,MSDN.10).gif
Figure 29
Finally, add another GridView to the page, binding it to the order details SqlDataSource. Once you have completed these two steps your ASP.NET page's declarative syntax should look similar to the following:
    Untitled Page


    

Select an Order from the Left...

... and View the Order Details on the Right

When examining the markup be sure to note the following:
  • When adding a Select button to a GridView, a CommandField is added. By default, the text for the Select button will be "Select," but this can be changed through the SelectText property. You can even use an image for the Select button, if you'd rather, by providing the path to the image in the SelectImageUrl property.
  • The orderGridView GridView's DataKeyNames property is set to OrderID. When a particular record in the GridView is selected, the GridView's SelectedValue property will be set to that row's OrderID value.
  • The orderDetailsDataSource SqlDataSource contains a parameter in its WHERE clause (@OrderID) whose value is specified in the section. The indicates that the parameter is of type Int32 and its value should be set to the orderGridView GridView's SelectedValue property.
Figures 30 and 31 show the drill-down report in action. Note that on the first page load, only the GridView of orders is displayed (see Figure 30). When an order's "View Order Details" link is clicked, a postback occurs and the order details GridView is bound to the SqlDataSource that returns all Order Details records associated with the selected order (see Figure 31).
Click here for larger image.
Figure 30 (Click on the graphic for a larger image)
Click here for larger image.
Figure 31 (Click on the graphic for a larger image)
One minor issue with the demo is that the orders GridView's SelectedIndex does not change when the GridView is paged. What this implies is that if you are on page 1 and click on the second order's "View Order Details," you will see that order's details to the right, as expected. However, if you then click to visit page 2, the second order on page 2 will be selected and its details will be shown to the right. I wanted to have the SelectedIndex reset when stepping through the pages. To accomplish this simply create an event handler for the GridView's PageIndexChanged event. The PageIndexChanged event fires whenever the user requests a new page of data. In this event handler I reset the GridView's SelectedIndex to -1, as shown in the following code snippet:
The PageIndexChanged Event Handler (Visual Basic)
Sub orderGridView_PageIndexChanged(ByVal sender As Object, _
   ByVal e As System.EventArgs)
    orderGridView.SelectedIndex = -1
End Sub
The PageIndexChanged Event Handler (C#)
void orderGridView_PageIndexChanged(object sender, EventArgs e)
{
    orderGridView.SelectedIndex = -1;
}

Drilling Down From Summary to Detail

The other flavor of drill-down reports is expanding from a concise view to a detailed view. For example, the Customers table in the Northwind database contains a plethora of fields and displaying all fields in a GridView would result in a wide, unwieldy GridView that was difficult to read. Rather than displaying all customer-related fields, it might make more sense to just display the pertinent fields—CompanyName and ContactName—along with a "View Customer Details" link in each row. If the end user wants to see all of the fields of a particular customer, they can click that customer's details link.
Creating such a summary to a detail drill-down report is fairly simple in ASP.NET 2.0 thanks to the DetailsView Web control, which is designed for displaying information one record at a time (as opposed to displaying numerous records at once, like the GridView). As we'll see shortly, displaying a particular customer's full details using a DetailsView is as simple as adding and configuring a GridView.
To get started we need to get just the CustomerID, CompanyName, and ContactName fields from the Customers table and display them in a GridView. As with our previous drill-down report example, this is accomplished by adding and configuring a SqlDataSource and then binding a GridView to it. Next, add another SqlDataSource that retrieves all of the Customers table's fields.
At this point you could add a WHERE clause and bind the parameter to the customer's GridView, just like we did in the previous drill-down example, but for this exercise let's try an alternative approach for accessing the correct customer for the customer DetailsView. After configuring the second SqlDataSource without adding a WHERE clause, from the Design view go to the SqlDataSource's Properties and add the following into the SqlDataSource's FilterExpression property: CustomerID='{0}'. Next, open the Parameter Collection Editor dialog box by clicking on the FilterParameters property. This dialog box should look familiar, as it closely mimics the dialog box shown in Figure 29 when we configured the WHERE clause parameter for the earlier drill-down report example. Set up a parameter based on the customer's GridView.
The last step is to add a DetailsView to the page. Add a DetailsView by simply dragging and dropping the control from the Toolbox and then, from its Smart Tag, associate it with the data source control we just configured.
Once you have configured this page your page's declarative syntax should look similar to the following markup shown. As with our previous examples, no source code was needed to create this page. When examining this markup be sure to take note of the following things:
  • The customerGridView GridView's DataKeyNames property is set to CustomerID. As we discussed with the previous drill-down report example, this indicates that when a GridView row is selected, the GridView's SelectedValue property will be set to the value of that row's CustomerID.
  • The customerDetailsDataSource SqlDataSource's SelectCommand does not include a WHERE clause. Instead, it contains a FilterExpressionCustomerID='{0}'—along with a section that indicates the filter parameter ({0}) has the value of the customerGridView GridView's SelectedValue property.





    Untitled Page


    

Select a Customer from the Left...

... and See Their Detailed Information on the Right

Figures 32 and 33 show the drill-down report in action.
Click here for larger image.
Figure 32 (Click on the graphic for a larger image)
Click here for larger image.
Figure 33 (Click on the graphic for a larger image)

GridView Examples for ASP.NET 2.0: Displaying Images in a GridView Column

In the ASP.NET 1.x class I teach, the course-long project for the students is to create an online photo album, one that allows visitors to upload images and provide metadata about the images, such as a description, a title, and so on. The data model my students typically use consists of a Pictures table with the following fields:
  • PictureID—a synthetic primary key, typically an integer field setup as an IDENTITY.
  • Title—a short title for the picture.
  • DateAdded—the date/time the picture was uploaded.
  • PictureUrl—the path to the uploaded image file.
When users want to add a new image to the photo album site, they must visit a particular page that contains a file upload control along with form input fields querying them for the other bits of information. When they submit the form, the picture on their computer is uploaded to the Web server's file system and a new row is added to the Pictures table. The PictureUrl field is set to the virtual path of the uploaded image file.
There's an additional page that lists all pictures in the photo album using a DataGrid. To display an image in a column in a DataGrid in ASP.NET 1.x you have to use a TemplateColumn with an Image Web control inside the TemplateColumn. With ASP.NET 2.0 the GridView includes an ImageField that can be used to display an image in a column of the GridView.
Imagine that we had the data model discussed previously and wanted to display all of the pictures in a GridView, displaying the PictureID, Title, and DateAdded fields each in a column and the actual image itself in an additional column.
To accomplish this we'd first grab the data using a data source control and then add a GridView bound to that data source control. This GridView would have four BoundField columns, meaning that instead of seeing the actual image we'd see the actual image path when viewing the GridView in a browser. To display the actual image, we need to edit the GridView's columns, removing the PictureUrl BoundField and replacing it with an ImageField. To edit a GridView's columns simply click on the Edit Columns link from the GridView's Smart Tag. This will bring up a dialog box like the one shown in Figure 25. Delete the PictureUrl BoundField and add in an ImageField. Finally, set the ImageField's DataImageUrlField to the name of the DataSource field that contains the image path—PictureUrl.
Aa479350.gridview_fg25(en-us,MSDN.10).gif
Figure 25
This will result in a GridView with the following declarative syntax:
Since the Northwind database does not have a table with an image path, we'll have to programmatically create our own data model to see this demo in action. The following code in our ASP.NET page creates a DataTable with the appropriate schema and populates the DataTable with four records.
Creating a DataTable Programmatically (Visual Basic)
Function GetData() As DataTable
    ' This method creates a DataTable with four rows.  Each row has the
    ' following schema:
    '   PictureID      int
    '   PictureURL     string
    '   Title          string
    '   DateAdded      datetime
    Dim dt As New DataTable()
    ' define the table's schema
    dt.Columns.Add(New DataColumn("PictureID", GetType(Integer)))
    dt.Columns.Add(New DataColumn("PictureURL", GetType(String)))
    dt.Columns.Add(New DataColumn("Title", GetType(String)))
    dt.Columns.Add(New DataColumn("DateAdded", GetType(DateTime)))
    ' Create the four records
    Dim dr As DataRow = dt.NewRow()
    dr("PictureID") = 1
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Blue hills.jpg")
    dr("Title") = "Blue Hills"
    dr("DateAdded") = New DateTime(2005, 1, 15)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 2
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Sunset.jpg")
    dr("Title") = "Sunset"
    dr("DateAdded") = New DateTime(2005, 1, 21)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 3
    dr("PictureURL") = _
      ResolveUrl("~/DisplayingImages/Images/Water lilies.jpg")
    dr("Title") = "Water Lilies"
    dr("DateAdded") = New DateTime(2005, 2, 1)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 4
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Winter.jpg")
    dr("Title") = "Winter"
    dr("DateAdded") = New DateTime(2005, 2, 18)
    dt.Rows.Add(dr)
    Return dt
End Function

Creating a DataTable Programmatically (C#)
DataTable GetData()
{
    // This method creates a DataTable with four rows.  Each row has the
    // following schema:
    //   PictureID      int
    //   PictureURL     string
    //   Title          string
    //   DateAdded      datetime
    DataTable dt = new DataTable();
    // define the table's schema
    dt.Columns.Add(new DataColumn("PictureID", typeof(int)));
    dt.Columns.Add(new DataColumn("PictureURL", typeof(string)));
    dt.Columns.Add(new DataColumn("Title", typeof(string)));
    dt.Columns.Add(new DataColumn("DateAdded", typeof(DateTime)));
    // Create the four records
    DataRow dr = dt.NewRow();
    dr["PictureID"] = 1;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Blue hills.jpg");
    dr["Title"] = "Blue Hills";
    dr["DateAdded"] = new DateTime(2005, 1, 15);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 2;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Sunset.jpg");
    dr["Title"] = "Sunset";
    dr["DateAdded"] = new DateTime(2005, 1, 21);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 3;
    dr["PictureURL"] = 
      ResolveUrl("~/DisplayingImages/Images/Water lilies.jpg");
    dr["Title"] = "Water Lilies";
    dr["DateAdded"] = new DateTime(2005, 2, 1);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 4;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Winter.jpg");
    dr["Title"] = "Winter";
    dr["DateAdded"] = new DateTime(2005, 2, 18);
    dt.Rows.Add(dr);
    return dt;
}

To bind this data to the GridView we can set the GridView's DataSource property to the GetData() method like so:

  ...


Finally, we need to call Page.DataBind() in the Page_Load event handler to bind the GridView's DataSource.
Page_Load Event Handler (Visual Basic)
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Page.DataBind()
End Sub
Page_Load Event Handler (C#)
void Page_Load(object sender, EventArgs e)
{
    Page.DataBind();
}

The end result is a GridView that shows the image referenced by the PictureUrl path (see Figure 26).
Aa479350.gridview_fg26(en-us,MSDN.10).gif
Figure 26
Don't be daunted by the length of this example's code—the length is due entirely to the fact that we had to synthetically create a data model with a table that has an image path field. Had the Northwind database had such a table, this example—like the previous ones—wouldn't have required a lick of code.

Upload and download a file from GridView in Asp.net using with C# and Vb || Gridview with file Download link button in Asp.net using with C# and Vb

The following article is showing about file uploading and downloading with Gridview in Asp.net.

First Design the source code with fileupload control and Gridview from Toolbox in Visual studio 2010.

Default.aspx:


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>title>

head>

<body>

<form id="form1" runat="server">

<div>

<asp:FileUpload ID="fileUpload1" runat="server" /><br />

<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />

div>

<div>

<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server"AutoGenerateColumns="false" DataKeyNames="FilePath">

<HeaderStyle BackColor="#df5015" />

<Columns>

<asp:BoundField DataField="Id" HeaderText="Id" />

<asp:BoundField DataField="FileName" HeaderText="FileName" />

<asp:TemplateField HeaderText="FilePath">

<ItemTemplate>

<asp:LinkButton ID="lnkDownload" runat="server" Text="Download"OnClick="lnkDownload_Click">asp:LinkButton>

ItemTemplate>

asp:TemplateField>

Columns>

asp:GridView>

div>

form>

body>

html>

Write the following code in Upload button click event and download link button click event in code behind side:


Default.aspx.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.IO;

public partial class _Default : System.Web.UI.Page

{

SqlConnection con = new SqlConnection("Data Source=naresh;Initial Catalog=student;User ID=sa;Password=123");

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindGridviewData();

}

}

private void BindGridviewData()

{

con.Open();

SqlCommand cmd = new SqlCommand("select * from FilesTable", con);

SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(ds);

con.Close();

gvDetails.DataSource = ds;

gvDetails.DataBind();

}

protected void btnUpload_Click(object sender, EventArgs e)

{

string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);

fileUpload1.SaveAs(Server.MapPath("Files/" + filename));

con.Open();

SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con);

cmd.Parameters.AddWithValue("@Name", filename);

cmd.Parameters.AddWithValue("@Path", "Files/" + filename);

cmd.ExecuteNonQuery();

con.Close();

BindGridviewData();

}

protected void lnkDownload_Click(object sender, EventArgs e)

{

LinkButton lnkbtn = sender as LinkButton;

GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;

string filePath = gvDetails.DataKeys[gvrow.RowIndex].Value.ToString();

Response.ContentType = "image/jpg";

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath +"\"");

Response.TransmitFile(Server.MapPath(filePath));

Response.End();

}

}



The following is the same code in Vb.net
 
Default.aspx.vb :
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Partial Public Class _Default
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=naresh;Initial Catalog=student;User ID=sa;Password=123")
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
BindGridviewData()
End If
End Sub

Private Sub BindGridviewData()
con.Open()
Dim cmd As New SqlCommand("select * from FilesTable", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
gvDetails.DataSource = ds
gvDetails.DataBind()
End Sub

Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
fileUpload1.SaveAs(Server.MapPath("Files/" & filename))
con.Open()
Dim cmd As New SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con)
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@Path", "Files/" & filename)
cmd.ExecuteNonQuery()
con.Close()
BindGridviewData()
End Sub

Protected Sub lnkDownload_Click(sender As Object, e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim filePath As String = gvDetails.DataKeys(gvrow.RowIndex).Value.ToString()
Response.ContentType = "image/jpg"
Response.AddHeader("Content-Disposition", "attachment;filename=""" & filePath & """")
Response.TransmitFile(Server.MapPath(filePath))
Response.[End]()
End Sub
End Class
 

Build your application and run it then you will get output like the following:


Google Ads by Mavra

About Me

My photo
Jeddah, Makkah, Saudi Arabia
for more details www.inhousetoday.com