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#
- Save and Display Image from DataBase
- Display image from database in asp mvc
- How to save image in database and display it into Views in MVC 4?
- Getting data from MS Access database and display it in a listbox
- How to Download Image From Url and Save It to a Local SQLite Database
- onchange display GridView record if exist from database using Javascript
- How to remove illegal characters from path and filenames?
- ASP.Net MVC: How to display a byte array image from model
- IdentityServer4 register UserService and get users from database in asp.net core
- How to sync model after using Code First from Database using Entity Framework 6.1 and MVC 5?
- What is the best way to connect and use a sqlite database from C#
- C# read a JPEG from file and store as an Image
- How to get file path from OpenFileDialog and FolderBrowserDialog?
- Loading PictureBox Image from resource file with path (Part 3)
- Create new URI from Base URI and Relative Path - slash makes a difference?
- Convert from a DataUrl to an Image in C# and write a file with the bytes
- Server not picking up information from database and passing it to client
- Can I get a path for a IsolatedStorage file and read it from external applications?
- Copying From and To Clipboard loses image transparency
- How to download an image from an URI and create a bitmap object from it?
- How to get full path from savefiledialog and use in "startInfo.Arguments"?
- Base64 image doesn't display on Render PDF from RDLC report
- Wrong file path and line number in Exception stack traces from dynamic code
- How to upload a image and display on same page in asp.net mvc 4
- Retrieve image from database in asp.net
- How can I embed a SQLite Database in a .NET DLL and then use it from C#?
- How to display image after selecting path in FileUpload controller without clicking
- Dynamically adding and loading image from Resources in C#
- Loading PictureBox Image From Database
- Reading and decoding PDF-417 barcodes stored in an image or PDF file from within a .NET application
- How to fix "Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')"
- Why are my EF Code First pregenerated views having no effect?
- How can I simulate a C++ union in C#?
- Why does the C# compiler allow empty enums?
- Resharper: Possible null assignment to entity marked with notnull attribute
- How to determine which CPU a thread runs on?
- How to implement decision tree with c# (visual studio 2008) - Help
- Array.Copy always row-major?
- How to call TypeConverter.ConvertTo or ConvertToString with InvariantCulture but without implementing ITypeDescriptorContext
- Exclude a file extension in System.IO.Directory.GetFiles()
- Is there a way to have a SetUpFixture that runs once per class instead of once per namespace?
- How to initialize double dimensional array with zero in c#
- Why are .NET value types sealed?
- C# While Loop vs For Loop?
- C# if statement within Javascript, Razor/MVC3
- What is the best way to generate KML files in C#?
- Is it possible to create a custom ASP.NET MVC strongly typed HTML Helper?
- WebApi POST not to include ID field
- calling base constructor passing in a value
- C# Crop & resize large images