In this post, We discuss how to save image in folder and path in the database table using FileUpload Control and then display uploaded images in a gridview.
In this post, we will cover the following points.
- Display Images in GridView Control using the path stored in SQL Server database
- How to show images from database in gridview in asp net
- How to display image in gridview from folder in asp.net c#
I have created a table in the database that will store the image path and name of the image.
CREATE TABLE [dbo].[Imagetable](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Filename] [nvarchar](150) NULL,
[Filepath] [nvarchar](250) NULL
)
- Open visual studio add new empty website
- File>>New>>Web Site then select “C# “Empty Web Site”
3.Now add a folder in your website name Images or anything else as you want.
Now I have added a Fileupload control, button, and a gridview and want to show all images in grid view.We want to display the images in GridView control. I have added 2 Bound Fields which displays ID and File Name and an Image Field.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Aimage.aspx.vb" Inherits="Aimage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Upload" />
</td>
</tr>
<tr>
<td colspan="2">
<Columns>
<asp:BoundField DataField = "ID" HeaderText = "ID" />
<asp:BoundField DataField = "FileName" HeaderText = "Image Name" />
<asp:ImageField DataImageUrlField="FilePath" ControlStyle Width="100" ControlStyle-Height = "100" HeaderText = "Preview Image"/>
</Columns>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
- Double click on upload button and write code on button click event.
- On button click we save the image in website folder and path in the database.Now i have created a method bindgridview() which bind gridview from database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
public partial class Aimage : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("Images/" + FileName)); //save picture into Images folder in the website
string imagepath= "Images/" + FileName;
SqlCommand cmd = new SqlCommand("insert into Imagetable (Filename,Filepath) values('" + FileName + "','"+imagepath+"')",con);
con.Open();
int i= cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
Response.Write("<script>alert('image uploaded successfully!')</script>");
bindgridview();
}
else
{
Response.Write("<script>alert('something went wrong try later!')</script>");
bindgridview();
}
}
}
public void bindgridview()
{
SqlCommand cmd = new SqlCommand("select * from Imagetable", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
Download Source Code
Now run the application and upload a image.
As we know that GridView is a very useful Asp .net control for displaying data from a database. Using GridView we can display items in the two-dimensional grid and provide more flexibility for displaying and working with data compared to other controls.Various features of GridView Control can be customized as per the requirement.
When we set the AutoGenerateColumns property of GridView Control to true, GridView Control examine our Data Object using Reflection and find all the properties of a Custom Object or all the Fields of a Record. Then create a Separate Column for each Field or Property in the same order in which they are found.
In this way, a GridView Control automatically creates columns based on the Field / Properties of its Record / Custom Object, which causes us to write any Extra Code to render a Custom Object or Record’s data to Output. However, many times we do not get the flexibility we need by GridView Control due to Automatically Create Columns.
For example, if we want to hide a column in our GridView Control, or change the order in which it is rendered, or change the heading text of those columns, then we need set AutoGenerateColumns Property to false to achieve all these requirements.
After setting this property to False, we have to manually specify the <Columns> section in the <GridView> Element.
The post Upload and Display an Image in Gridview From Image Path in Database -C# appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- Retrieve image and display in picturebox with image path stored in database c#
- How to Fetch and Display an Image from the Database in ASP.Net and C#
- how to display G map by repeater and markers from database
- How to display data from database into textbox, and update it
- Upload,Save and Retrieve Image from database by using their Id in Code First Method
- How to display an image from path in MVC 4?
- Resize and Display image from server with ASP.NET
- Load and display image from a url
- Display image from database in _layout in mvc4
- Retrive image file from folder and display into Image Control
- ASP.NET: How to display a different value returned from a database in a GridView
- Create a BitmapImage from a Byte array and display it on an Image object UWP Raspberry Pi 3
- Unable to display an image from database in asp.net view
- Get bit value from database and show in CheckBox in GridView
- I want to retrieve an Image from database and crop it as per the user needs
- How can I get a username and password from my database in C#?
- How to save a combination of text and image in SQL Server database
- Image Resizing from SQL Database on the fly with MVC2
- Reading an SQLite DateTime value from database and assigning it to a C# string variable
- Capture signature using HTML5 and save it as image to database
- How do I prevent a form from closing and display a confirmation dialog?
- How can I display an image from SQL Server using ASP.NET?
- Attaching Multiple Files To An E-Mail From Database Image Column In .NET
- How to delete a selected row from datagridview and database
- C# string handling how get path and args from a string
- Display image in view from file system
- Umbraco display images created from image cropper using razor
- Easily create database tables from logical model in .NET and VS
- How to display image in WinForms and then delete?
- Zoom and translate an Image from the mouse location
- When are async and await needed in c#?
- How to cast float to double without extra digits added?
- How can I generate a safe class name from a file name?
- Container not disposing transient components
- In a C# application, where does Windows grab the name of process when it appears in the Task Manager?
- How does NetworkCredential in C# works when assigned to a HttpRequest object?
- Using RenderTargetBitmap on WindowsFormsHost
- UserPrincipal extensions returns computers
- Mp4 playback in XNA using DirectShow.Net
- What mistake am I making when serializing?
- C# Rhino.Mocks - How do I write test code without repeating myself?
- OpenXml WorksheetParts.First() is not always the 1st sheet MS Excel shows
- Why does FxCop insist on IDisposable for a struct
- Show WPF window from another application in C#
- WPF- How to get selected row index in datagrid?
- LinkButton or HyperLink?
- What does 'this' mean in a c# constructor?
- What is the rationale not to use ArrayList in Silverlight?
- How does font fallback work on a non-Windows OS?
- Authentication to Sharepoint Online with CSOM