This tutorial will show how we can upload files to a SQL database using ASP.NET and C#.

In this tutorial, we will be using a FileUpload Control to allow uploading of files to a SQL database. For this example, the database has just one table and five columns:
id, name, img, type, and length.We add a FileUpload control, a button, a GridView and two SqlDataSources to the ASPX page:

Note there are two SqlDataSources – one is for adding new files to the database, the other is for displaying (and deleting) files to (and from) the GridView.
Also note the CommandField, which allows deletion from the GridView.

In the code-behind, we can ask if the file already exists, and if it does, we will delete the existing file and then save the new one – effectively overwriting it. Then we bind the data to the GridView to update the display.
On the ContentDataSource_Inserting event, we set the values of the uploaded image to the column names of table within the database – inserting a new record.
Similarly, on the ContentDataSource_Deleting even, we delete the record from the database by name.
The code-behind should look something like this:

The ConnectionString in Web.config should be something like this:

Download Source Files