image handler file error

Posted by Sugi under C# on 11/29/2012 | Points: 10 | Views : 1810 | Status : [Member] | Replies : 1
how to solve
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]' while using .ashx file




Responses

Posted by: Sandhyab on: 11/29/2012 [Member] Starter | Points: 25

Up
0
Down
Once see this example. Check whether data is null in you db. It is showing as null.. That is why casting error has occured.

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


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

public class ShowImage : IHttpHandler {

public void ProcessRequest (HttpContext context) {
if (context.Request.QueryString["ProductId"] == null) return;
string ProductId = context.Request.QueryString["ProductId"];
string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Item FROM BookDetails WHERE ProductId = @ProductId", conn))
{
cmd.Parameters.Add(new SqlParameter("@ProductId", ProductId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Item")]);
reader.Close();
}
}
}
}

public bool IsReusable {
get {
return false;
}
}

}


Sugi, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response