Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
aspx.cs code....

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class Image_uploading : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
           {
      BindGridData();
        }
       }

   
     protected void btnUpload_Click(object sender, EventArgs e)
     {
       
         if (fileuploadImage.HasFile)
{

int length = fileuploadImage.PostedFile.ContentLength;

byte[] imgbyte = new byte[length];

HttpPostedFile img = fileuploadImage.PostedFile;

img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;

SqlConnection connection = new SqlConnection("Data Source=CIODEV03\\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True");
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image1 (ImageNAme,Image) VALUES (@imagename,@imagedata)", connection);
cmd.Parameters.Add("@ImageNAme", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();

if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
  

     private void BindGridData()
     {
         SqlConnection connection = new SqlConnection("Data Source=CIODEV03\\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT ImageNAme,ImageId from [Image1]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
//DataSet ds = new DataSet();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
     }








aspx code....


XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Image uploading.aspx.cs" Inherits="Image_uploading" %>

<!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 id="Head1" runat="server">
<title>Inserting images into databse and displaying images with gridview</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
width:500px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Image Name:
</td>
<td>
<asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Upload Image:
</td>
<td>
<asp:FileUpload ID="fileuploadImage" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>

<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageNAme") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>







C#
<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

public class ImageHandler : IHttpHandler {
    string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
    
    public void ProcessRequest (HttpContext context) 
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
        string ImageId = context.Request.QueryString["ImageId"];
        SqlConnection connection = new SqlConnection("Data Source=CIODEV03\\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True");
        connection.Open();
        SqlCommand command = new SqlCommand("select Image from Image1 where ImageId=" + ImageId, connection);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        connection.Close();
        context.Response.End();
    }
 
    public bool IsReusable
    {
        get {
            return false;
        }
    }

}



error......


Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 7:  
Line 8:  public class ImageHandler : IHttpHandler {
Line 9:      string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
Line 10:     
Line 11:     public void ProcessRequest (HttpContext context)
Posted
Updated 16-Feb-12 20:37pm
v2

Check 
"ConnectionString" key exists in web config file if not then add or remove it 

ConfigurationManager.AppSettings["ConnectionString"]
 
Share this answer
 
Hi,

You said u got the Error at:

Line 7:
Line 8: public class ImageHandler : IHttpHandler {
Line 9: string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
Line 10:
Line 11: public void ProcessRequest (HttpContext context)

I think u r getting the error at ConfigurationManager.Appsettings["ConnectionString"].ToString();

May be you didn't add the Connection string in the

<ConnectionStrings>
<add name="ConnectionString" connectionString="Data Source=Server; initial catalog=database; User ID=id;Password=pwd;" providerName="System.Data.SqlClient"/>
</ConnectionStrings>

option in web.config.
 
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