Upload Image, Save In Database, And Show In Gridview

Introduction

 
In this article, I will tell you how you can save an image in your solution folder, get its path and save it in a database, and also how you show that image with other data in grid view. I hope you will like this article.
 
Step 1
 
Open Visual Studio.
 
Step 2
 
Click on file menu then select New option then click on project. It will open a new popup window.
 
Upload Image Save In Database And Show In Gridview
 
Step 3
 
In this step, you will get a popup window where you need to select your project template. Here we are creating our project in ASP.NET, so first search asp.net in the search bar, it will give you some results like ASP.NET core application, ASP.NET web application (.Net framework), and ASP.NET web site (Razor), etc... Select ASP.Net Web Application (.Net Framework) and click on the Next button.
 
Upload Image Save In Database And Show In Gridview
 
Step 4
 
After clicking on next button, you get a new popup window where you need to enter the following details.
  • Project Name: in this field, you need to enter your project name.
  • Location: select your path/folder location from your local computer where you want to save your project.
  • Solution Name: give your solution name, this name shows in solution explorer after your project opens in Visual studio.
  • Framework: select a version of .NET Framework. Now click on the Create button.
Upload Image Save In Database And Show In Gridview
 
Step 5
 
In the next step, you will get a pop up window with various types of templates. In this window there are the following templates.
  • Empty
    An empty project template for creating ASP.Net application. This template does not have any content in it.

  • Web Forms
    A project template for creating ASP.Net web forms application.ASP.Net web form lets you build a dynamic website using a familiar drag and drop, event-driven model. A design surface and hundreds of controls and components let you rapidly build a sophisticated, powerful UI-driven site with data access.

  • MVC
    A project template for creating an ASP.NET MVC application. ASP.NET MVC allows you to build applications using the model-view-controller architecture. ASP.NET MVC includes many features that enable fast, test-driven development for creating applications that uses the latest standards.

  • WEB API
    A project template for creating RESTful HTTP service that can reach of clients including browser and mobile device.

  • Single Page Application
    A project template for creating rich client-side Javascript driven HTMPL5 application using ASP.NET web API. Single page application provides a rich user experience which includes client-side interaction using HTML5 CSS3 and JavaScript.
Upload Image Save In Database And Show In Gridview
 
Now click on the Create button. Now your project is created and it will open in visual studio. Your project is created successfully now first of all we need to add a database to our project for storing our data. In the ASP.NET website we add database file in our project folder and also we can user database from SQL Server Management Studio. But in this article, we will use the first one.
 
Step 6
 
For add database in your project right click on project name then click on Add option and then Click on New Item. You can also use short cit key to add new item Ctrl+Shift+A.
 
Upload Image Save In Database And Show In Gridview 
 
Step 7
 
After clicking on New Item, you will get a new popup window. In this window select Data from side bar then you will show the only item which uses as data, from that options select SQL Server Database . Give your database name and click on Add button.
 
Upload Image Save In Database And Show In Gridview 
 
After clicking on the Add button you will see a warning pop up which tells you that "You are attempting to add a special file type to an ASP.Net Web site in General, to use this type of item in your site, you shold place ite in the App_Data folder". If you click on ok it will create a new folder App_Data in your project and save database file in that folder and if you click on No button it will save database file in the main directory of your project.
 
Upload Image Save In Database And Show In Gridview
 
Step 8
 
Now we need to add a new table in our database. To add a new table double click on database file from your solution explorer, it will open your database in server explorer. Expand your database > Right click on Table folder > Click on Add New Table Option.
 
Upload Image Save In Database And Show In Gridview
 
Step 9
 
Now you see a design and query layout for add table in your data base create a table with fields as you need. Here I created a table with the following fields
 
1) Id : with int datatype and auto increament of 1
2) ImageName : with varchar datatype for store image name
3) ImagePath : with varchar datatype for store path of image
  1. CREATE TABLE [dbo].[ImageExample] (    
  2.     [Id]        INT           NOT NULL IDENTITY,    
  3.     [ImageName] VARCHAR (50)  NULL,    
  4.     [ImagePath] VARCHAR (150) NULL,    
  5.     PRIMARY KEY CLUSTERED ([Id] ASC)    
  6. ); 
Step 10
 
After create table now we need to use that database in our project so first of all wee need to add connection string in web.config file so we can easily access that connection string in all over our project. for add connection string right click on Database name then click in Modify Connection option.
 
Upload Image Save In Database And Show In Gridview
 
Step 11
 
Now you get one popup where you see your database location, data source, and authentication options. Click on the advance button. It will open another window.
 
Upload Image Save In Database And Show In Gridview 
 
Step 12
 
In this window copy the data source path and click on the Ok button. This window closes and you see the previous window. Click the ok button there also.
 
Upload Image Save In Database And Show In Gridview
  1. <connectionStrings>    
  2.   <add name="MyString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Website\UploadImageAndShowInGrid\UploadImageAndShowInGrid\App_Data\Database.mdf;Integrated Security=True" />     
  3. </connectionStrings>   
Step 13
 
Now we successfully created our database so now we need to add a web page in our project. We select an empty template for our website so there is no web page in our project. To add new web form in our project Right click on pro name > Click on Add option and then click On New item. you can also use short cut key Ctrl+Shift+A for add new items.
 
Upload Image Save In Database And Show In Gridview
 
Step 14
 
Select the web option from the left sidebar. Then it shows option only acording to web, select Web Form and give it an appropriate name and click on the Add button.
 
Upload Image Save In Database And Show In Gridview 
 
Step 15
 
Now create a design for image uploader as you need.
 
Step 16
 
In this article for show data in grid view, we will user SqlDataSource component. Add SqldataSource from toolbox in your web form and then click on the arrow button and click on the configure data source option. It will open the popup window. We need to add a data source form, SQLDataSource Component.
 
Upload Image Save In Database And Show In Gridview
 
Step 17
 
In the popup window, there is the first step to select a database from the dropdown list which you want to use in your project. Then click on the Next button.
 
Upload Image Save In Database And Show In Gridview 
 
Step 18
 
In the next step, you asked to add a connection string in the web.config file if you check this, it will add a new connection string in web.config file. We already add connection string in the config file so we click on the next button without checking that box.
 
Upload Image Save In Database And Show In Gridview 
 
Step 19
 
In next step you perform some steps like:
  • Select your table
  • select colums which you want to use, you can only check * if you want all columns.
  • You can also use where and order by clause.
  • Now click on the Next button.
Upload Image Save In Database And Show In Gridview
 
Step 20
 
In this final step if your table has any data you can show that preview by click on the Test Query button. Now click on the Finish button.
 
Upload Image Save In Database And Show In Gridview 
 
Step 21
 
Now we need to add a grid view in our form. Select grid view from the toolbox .
 
Step 22
 
Click on the arrow button and choose the data source which we recently added in our page.
 
Upload Image Save In Database And Show In Gridview
After selecting the data source, it shows a warning message that "Would you like to regenerate the Gridview column field and data key using the selected data source schema ? ". if you click on yes then it will delete all existing columns from your gridview and create a new one as per the data source.
 
Upload Image Save In Database And Show In Gridview
 
Step 23
 
Now click on the arrow button of grid view and click on the Edit column option. It will open a new popup window.
 
Step 24
 
In this window, you need to perform the following task.
  • Delete the image field from selected fields by click on the X button.
  • Add TemplateField by click on the add button.
  • Give the header text of that field.
  • Click on the Ok button.
Upload Image Save In Database And Show In Gridview  
 
Step 25
 
Now Select Edit template option by click on the arrow button in gridview.
 
Upload Image Save In Database And Show In Gridview
 
Step 26
 
Add an image from the toolbox and click on edit DataBindings.
 
Upload Image Save In Database And Show In Gridview
Step 27
 
Select ImageUrl property from the left side and select the image path column of the database table from dropdown. Then click on the Ok button.
 
Upload Image Save In Database And Show In Gridview 
 
Step 28
 
The design of the web page is complete. Now we need to code in the back end. Double click anywhere on the form. It will generate a form load event. Replace the event with the following code.
  1.         SqlConnection cn;  
  2.         SqlCommand cmd;  
  3.         string cs = ConfigurationManager.ConnectionStrings["MyString"].ConnectionString.ToString();  
  4.         protected void Page_Load(object sender, EventArgs e)  
  5.         {  
  6.             cn = new SqlConnection(cs);  
  7.             cn.Open();  
  8.         }  
Code Explanation
  • We define two variables of SQLConnection and SQLCommand type. If you get an error in that line import System.Data.SqlClient namespace.
  • Then we define string variable "cs" in that variable we get the connection string from web.config file. you need to import System.Configuration namespace for user ConfigurationManager.
  • In Page_Load event initialize SQLConnection variable by giving cs string variable to it.
  • Then open connection By Open() Method.
Step 29
 
Now we need to code on the Button click event. Double click on your button and add the following code.
  1.         protected void Button1_Click(object sender, EventArgs e)  
  2.         {  
  3.             if (FileUpload1.HasFile)  
  4.             {  
  5.                 string fileName = FileUpload1.FileName;  
  6.                 string folderPath = Server.MapPath("~/Images");  
  7.                 string image = "/Images/" + fileName;  
  8.                 string storeImage = folderPath + fileName;  
  9.                 if (!Directory.Exists(folderPath))  
  10.                 {  
  11.                     Directory.CreateDirectory(folderPath);  
  12.                 }  
  13.                 FileUpload1.SaveAs(storeImage);  
  14.   
  15.                 cmd = new SqlCommand("insert into ImageExample (ImageName,ImagePath) values('" + fileName + "','" + image + "')", cn);  
  16.                 cmd.ExecuteNonQuery();  
  17.                 lblMsg.Text = "Image upload successfully";  
  18.                 lblMsg.ForeColor = Color.Green;  
  19.                   
  20.                 GridView1.DataBind();  
  21.   
  22.             }  
  23.             else  
  24.             {  
  25.                 lblMsg.ForeColor = Color.Red;  
  26.                 lblMsg.Text = "Please select Image";  
  27.             }  
  28.   
  29.         }  
Code Explanation
  • First of all compiler check, that file uploder has any files if not then it shows a message in the label which we define in aspx file.
  • Then define some variables like fileName for store name of the file , folderPath for store folder with current solution location, image for the folder and image both path compbine and storageImage for the whole path of the image.
  • Then compiler checks if folder exists. If not, then it will create one.
  • Then we save files from fileuploder to our folder.
  • Then store data in the database table and show the message in the label.
  • In the last refresh grid by call DataBind method.
Step 30
 
Now run your application and test it.
Upload Image Save In Database And Show In Gridview

Summary

 
So in this article, we created, saved, and displayed an image in gridview. If you have any questions, you can ask in the comments below. If you get any help from this article, kindly like and share it.Thank you.