Click here to Skip to main content
15,569,840 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
using this code i want to upload image and show on page_load..
but its doing nothing please help


C#
public void BindGridData()

        {
            string username=(string)(Session["UserAuthentication"]);
            SqlConnection con = new SqlConnection(connstring);
            SqlCommand cmd = new SqlCommand("SELECT imgname from [Image] WHERE imgname='" + username + "'", con);
            SqlDataReader sdr;
            con.Open();
            sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                Image1.ImageUrl = sdr[0].ToString();
            }
            con.Close();
        }
protected void Button2_Click1(object sender, EventArgs e)
        {

if (FileUpload1.HasFile)
{

int length = FileUpload1.PostedFile.ContentLength;

byte[] imgbyte = new byte[length];

HttpPostedFile img = FileUpload1.PostedFile;

img.InputStream.Read(imgbyte, 0, length);
string username=(string)(Session["UserAuthentication"]);

SqlConnection connection = new SqlConnection(connstring);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (imgname,Image) VALUES (@imgname,@imagedata)", connection);
cmd.Parameters.Add("@imgname", SqlDbType.VarChar, 50).Value = username;
cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();

ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + username + " image inserted successfully')", true);
}
}
 public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            
            string imageid = context.Request.QueryString["ID"];
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\VAS\Desktop\Orignal Project Part 1\Inventory Management System\IMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
            conn.Open();
            SqlCommand command = new SqlCommand("select Image from Image where imgname=" + imageid, conn);
            SqlDataReader dr = command.ExecuteReader();
            dr.Read();
            context.Response.BinaryWrite((Byte[])dr[0]);
            conn.Close();
            context.Response.End();
}


ASP.NET
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ID="+ Eval("imagename") %>'  Height="267px" 
          Width="768px" />
Posted
Updated 17-Jun-13 3:24am
v2

1 solution

you need to add file to add images in it like "images"
then add this code
FileUpload1.SaveAs(Server.MapPath("~/images/") + imageName);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900