image upload to database and display in gridview

Manimaddu
Posted by Manimaddu under ASP.NET category on | Points: 40 | Views : 406
Hi All..
In this i will show how to upload an image into database and display in grid view.

Create Table tbl_imageupload with column UserName,Name and Path.



CREATE TABLE tbl_imageupload (
UserName VARCHAR(30) NOT NULL,
ImageName VARCHAR(30),
Path VARCHAR(30)
)


Create a procedure usp_imageUpload to insert the details into table



CREATE PROCEDURE usp_ImageUpload
(
@UserName VARCHAR(30),
@ImageName VARCHAR(30),
@Path VARCHAR(30)
)
AS
BEGIN
INSERT INTO usp_ImageUpload (UserName,ImageName,Path)VALUES(@UserName,@ImageName,@Path)
END


This is aspx page


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="upload.aspx.cs" Inherits="imageUpload.upload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:ImageField HeaderText="Profile Picture" DataImageUrlField="Path"/>
</Columns>
</asp:GridView>
<asp:Label ID="lblname" runat="server" Text="Enter Youe Name"></asp:Label>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:FileUpload ID="UploadImages" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
Text="Submit" />

</div>
</form>
</body>
</html>



This is aspx.cs Page



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.IO;
using System.Web.Configuration;

namespace imageUpload
{
public partial class upload : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["db"].ToString());
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
string filename = Path.GetFileName(UploadImages.PostedFile.FileName);
UploadImages.SaveAs(Server.MapPath("~/" + filename));
con.Open();
SqlCommand cmd = new SqlCommand("usp_ImageUpload", con);
cmd.CommandType = CommendType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserName", txtname.Text);
cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@Path", "~/" + filename);
cmd.ExecuteNonQuery();
con.Close();
fill();
}
catch (Exception ex)
{
Response.Write(ex.Message);

}
}
public void fill()
{
SqlDataAdapter da = new SqlDataAdapter("select Path from tbl_imageupload where UserName ='" + txtname.Text + "'", con);
DataTable dt1 = new DataTable();
da.Fill(dt1);
GridView1.DataSource = dt1;
GridView1.DataBind();
}
}
}

Thank You...

Comments or Responses

Login to post response