I want to retrieve image from oracle database
and show it in Image control I tried but it is showing empty image
Code for Insert Image:
protected void btnUpload_Click(object sender, EventArgs e)
{
int imgLength = 0;
string imgContentType = null;
string imgFileName = null;
Stream imgStream = FileUpload.PostedFile.InputStream;
imgLength = FileUpload.PostedFile.ContentLength;
imgContentType = FileUpload.PostedFile.ContentType;
imgFileName = FileUpload.PostedFile.FileName;
if (imgContentType == "image/jpeg" || imgContentType == "image/gif" ||
imgContentType == "image/pjpeg"
|| imgContentType == "image/bmp")
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
FileStream fls;
fls = new FileStream(#imgFileName, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
string query = "insert into image(id,name,photo) values(1,'" + imgFileName + "'," + " :BlobParameter )";
// Establish a new OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.CommandText = query;
cmd.Connection = DbConnection;
cmd.CommandType = CommandType.Text;
System.Data.OracleClient.OracleParameter paramImage = new System.Data.OracleClient.OracleParameter("image",
Oracle.DataAccess.Client.OracleDbType.Blob);
paramImage.ParameterName = "BlobParameter";
paramImage.Value = blob;
paramImage.Direction = ParameterDirection.Input;
cmd.Parameters.Add(paramImage);
cmd.ExecuteNonQuery();
}
}
Table:
Id Name Photo
1 C:\Document\Image\Ocean.jpeg (BLOB)
In the below code I'm trying to retrieve and show that image in image control
but it's not working
Code for retrieve:
void GetImagesFromDatabase()
{
try
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
OracleCommand cmd = new OracleCommand("Select name from Image", DbConnection);
OracleDataReader oda = cmd.ExecuteReader();
while (oda.Read())
{
string path = oda[0].ToString();
img.ImageUrl = path;
}
}
catch (Exception ex)
{
}
}
Any ideas? Thanks in advance
Related
I want get an image from a Blob in MySQL then display image in a PictureBox. My incoming image is not correct and I don't understand how I can retrieve the byte array because my current array is not correct.
My code:
add img into database:
using(OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
byte[] bytes = File.ReadAllBytes(ofd.FileName);
imageUrl = ofd.FileName.ToString();
//roundPictureBox1.Image = Image.FromFile(ofd.FileName);
roundPictureBox2.ImageLocation = imageUrl;
MySqlConnection con = new MySqlConnection(connectionString);
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO reg.img_table(image, id) VALUES (#image, #id)", con);
long id = cmd.LastInsertedId;
Properties.Settings.Default.idImg = id;
cmd.Parameters.AddWithValue("#image", bytes);
cmd.Parameters.AddWithValue("#id", id);
cmd.ExecuteNonQuery();
con.Close();
}
}
return Img:
private Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
main code:
private void photoLoad()
{
string connectionString = "datasource=localhost;" +
"port=3306;" +
"database=reg;" +
"username=root;" +
"password=Admin123";
MySqlConnection con = new MySqlConnection(connectionString);
byte[] ImageByte = new byte[0];
string query1 = "select image from reg.img_table where id= #id";
MySqlCommand cmd = new MySqlCommand(query1, con);
cmd.Parameters.AddWithValue("#id", Properties.Settings.Default.idImg);
try
{
con.Open();
MySqlDataReader row;
row = cmd.ExecuteReader();
while (row.Read())
{
ImageByte = (Byte[])(row["image"]);
}
if (ImageByte != null)
{
// You need to convert it in bitmap to display the image
roundPictureBox1.Image = byteArrayToImage(ImageByte);
roundPictureBox1.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show("Error Img");
}
}
An error doesn't show. The login form shows but PictureBox doesn't show the photo.
According to your OP, you're storing your image in a database BLOB column in a MySql database. The following shows how to insert an image into a MySql database table. Then retrieve that image and display it in a PictureBox.
Download/install NuGet package: MySql.Data
Database Table: Student
I've chosen to store the connection string for the database in App.config.
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MySqlConnectionString" connectionString="Server=localhost;Port=3306;Database=University123;Uid=testAdmin;Pwd=password123;" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
Create a class: (name: HelperMySql.cs)
In VS menu, click Project
Select Add Class...
Add the following using statements:
using System.Configuration;
using System.IO;
using MySql.Data.MySqlClient;
HelperMySql.cs
Note: I've chosen to use LongBlob instead of Blob - this can be changed, if desired.
public class HelperMySql
{
private string _connectionStr = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;
//private string _connectionStr = "Server=localhost;Port=3306;Database=University123;Uid=testAdmin;Pwd=password123;";
public void ExecuteNonQuery(string sqlText)
{
using (MySqlConnection con = new MySqlConnection(_connectionStr))
{
//open
con.Open();
using (MySqlCommand cmd = new MySqlCommand(sqlText, con))
{
//execute
cmd.ExecuteNonQuery();
}
}
}
public byte[] GetImageAsByteArray(string filename)
{
//reads image from file and returns as byte[]
if (String.IsNullOrEmpty(filename))
throw new Exception("Error (GetImageAsByteArray) - Filename not specified.");
else if(!File.Exists(filename))
throw new Exception($"Error (GetImageAsByteArray) - File '{filename}' doesn't exist.");
return System.IO.File.ReadAllBytes(filename);
}
public void TblStudentCreate()
{
//for mySQL, use backticks (ex: `First Name`) if tablename has space in it
string sqlText = #"CREATE TABLE Student (Id int NOT NULL AUTO_INCREMENT,
FirstName varchar(50),
LastName varchar(75),
Img longblob,
CONSTRAINT PK_Student_ID PRIMARY KEY(ID));";
ExecuteNonQuery(sqlText);
Debug.WriteLine("Info: Table created (Student)");
}
public void TblStudentInsert(string firstName, string lastName, string filename)
{
if (String.IsNullOrEmpty(filename))
throw new Exception("Error (TblStudentInsert) - Filename not specified.");
else if (!File.Exists(filename))
throw new Exception($"Error (TblStudentInsert) - File '{filename}' doesn't exist.");
byte[] imageBytes = File.ReadAllBytes(filename);
TblStudentInsert(firstName, lastName, imageBytes);
}
public void TblStudentInsert(string firstName, string lastName, byte[] imageBytes)
{
string sqlText = "INSERT INTO Student (FirstName, LastName, Img) VALUES (#firstName, #lastName, #imageBytes);";
using (MySqlConnection con = new MySqlConnection(_connectionStr))
{
//open
con.Open();
using (MySqlCommand cmd = new MySqlCommand(sqlText, con))
{
//add parameters
//FirstName
if (!String.IsNullOrEmpty(firstName))
cmd.Parameters.Add("#firstName", MySqlDbType.VarChar).Value = firstName;
else
cmd.Parameters.Add("#firstName", MySqlDbType.VarChar).Value = DBNull.Value;
//LastName
if (!String.IsNullOrEmpty(lastName))
cmd.Parameters.Add("#lastName", MySqlDbType.VarChar).Value = lastName;
else
cmd.Parameters.Add("#lastName", MySqlDbType.VarChar).Value = DBNull.Value;
//Img
if (imageBytes != null)
cmd.Parameters.Add("#imageBytes", MySqlDbType.LongBlob).Value = imageBytes;
else
cmd.Parameters.Add("#imageBytes", MySqlDbType.LongBlob).Value = DBNull.Value;
//execute
cmd.ExecuteNonQuery();
}
}
}
public byte[] GetStudentImage(int id)
{
string sqlText = "SELECT img from Student where Id = #id;";
using (MySqlConnection con = new MySqlConnection(_connectionStr))
{
//open
con.Open();
using (MySqlCommand cmd = new MySqlCommand(sqlText, con))
{
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = id;
//execute
using (MySqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while(dr.Read())
{
//get image from database and return as byte[]
if (dr["Img"] != null && dr["Img"] != DBNull.Value)
return (byte[])dr["Img"];
}
}
}
}
}
return null;
}
}
Usage: Insert Record to Database
private HelperMySql helper = new HelperMySql();
...
helper.TblStudentInsert("John", "Smith", #"D:\Images\Students\JohnSmith.png");
Usage: Display Image in PictureBox (name: pictureBox1)
int studentId = 1;
byte[] imageBytes = helper.GetStudentImage(studentId);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
pictureBox1.Image = Image.FromStream(ms);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //fit to size
pictureBox1.Refresh();
}
Note: You may consider storing the filenames in the database, and store the actual files in the file system instead.
Resources:
MySQL 8.0 Reference Manual
Data Type Storage Requirements
This is my code for which I am getting the above said error when trying to delete the tournament. Since Tournament is associated with an image, the code calls the ImageDeletion function first and then the tournament count function before deleting the whole tournament.
protected void LVTournament_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
if (Session["TournId"] != null)
{
int ClubId = Convert.ToInt32(Request.Cookies["ClubDetails"]["ClubId"]);
int TournId = Convert.ToInt32(Session["TournId"]);
SqlConnection con1 = new SqlConnection(constr);
SqlConnection con2 = new SqlConnection(constr);
ImageDeletion(TournId);
string querydelTour = "DELETE FROM Tournaments WHERE TournamentId = #TournId";
SqlCommand cmd1 = new SqlCommand(querydelTour, con1);
cmd1.Parameters.AddWithValue("#TournId", TournId);
con1.Open();
cmd1.ExecuteNonQuery();
con1.Close();
UpdateTourCount(ClubId);
ClientScript.RegisterStartupScript(Page.GetType(), "Success", "<script language='javascript'>alert('Tournament Deleted...')</script>");
Response.Redirect("TournamentView.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "Popup", "SessionExpires();", true);
return;
}
}
The Image Deletion function is
private void ImageDeletion(int TournId)
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmdchk = new SqlCommand("SELECT count(*) Valid FROM TournamentImages WHERE TournamentId= #TournId");
cmdchk.Connection = con;
cmdchk.Parameters.AddWithValue("#TournId", TournId);
con.Open();
int Count = (int)cmdchk.ExecuteScalar();
for (int i = 0; i <= Count; i++)
{
string query = "SELECT ImagePath FROM TournamentImages WHERE TournamentId = #TournId";
SqlCommand cmddel = new SqlCommand(query, con);
cmddel.Parameters.AddWithValue("#TournId", TournId);
SqlDataReader reader = cmddel.ExecuteReader();
while (reader.Read())
{
string FilePath = reader[0] as string;
string path = Server.MapPath(FilePath);
FileInfo file = new FileInfo(path);
if (file.Exists)
{
file.Delete();
}
}
}
con.Close();
}
And the tournament count function is
protected void UpdateTourCount(int ClubId)
{
SqlConnection con = new SqlConnection(constr);
string Query = "UPDATE TournamentCount SET Count = Count + 1 WHERE ClubId =#ClubId";
SqlCommand cmd = new SqlCommand(Query, con);
cmd.Parameters.AddWithValue("#ClubId", ClubId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I have close the connections then and there and still I am getting this error.
Kindly mention me where am I making the mistake. Thanks in advance
Your error message should give you a tip what is going on. It says "There is already an open DataReader ...". So you have closed the connections, but not the reader.
You should call method Close after you have used reader:
SqlDataReader reader = cmddel.ExecuteReader();
while (reader.Read())
{
string FilePath = reader[0] as string;
string path = Server.MapPath(FilePath);
FileInfo file = new FileInfo(path);
if (file.Exists)
{
file.Delete();
}
}
reader.Close(); // <- close the reader
SqlDataReader implements IDisposable, so you can alternativelly use using statement to achieve the same result:
using(SqlDataReader reader = cmddel.ExecuteReader())
{
while (reader.Read())
{
string FilePath = reader[0] as string;
string path = Server.MapPath(FilePath);
FileInfo file = new FileInfo(path);
if (file.Exists)
{
file.Delete();
}
}
}
They're must be a minor error somewhere in my code that im not seeing as to why on my web page , the gridview only outputs one row when i know the query works/
Both rows from management studio
Only one row in ASP page
heres my c#
string AdminID = Request.QueryString["ID"];
string AdminsCurrentLocation = Request.QueryString["Location"];
//retrieve admin location
try
{
string connectionString = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
//
// Create new SqlConnection object.
//
using (SqlConnection connection5 = new SqlConnection(connectionString))
{
connection5.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM [DB_A05369_WATERQ].[dbo].[S_CONTROL] WHERE LOGIN = '" + AdminID + "'", connection5))
{
//
// Invoke ExecuteReader method.
//
using (SqlDataReader reader2 = command.ExecuteReader())
{
reader2.Read();
TempLocationIdbox.Text = (reader2["ALL_LOCATION_ACCESS"].ToString());
}
}
connection5.Close();
}
}
catch (Exception ex) { }
if(TempLocationIdbox.Text == "Y")
{
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM " +
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM " +
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND ACT.LOCATION_ID = LOC.ROW_ID AND ACT.MEMBER_ID = MEM.ROW_ID", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
else if (TempLocationIdbox.Text == "N")
{
string strSQLconnection1 = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection1 = new SqlConnection(strSQLconnection1);
SqlCommand sqlCommand1 = new SqlCommand("SELECT * FROM S_LOCATION WHERE NAME = '" + AdminsCurrentLocation + "'", sqlConnection1);
sqlConnection1.Open();
string locationrowID = "";
SqlDataReader reader12 = sqlCommand1.ExecuteReader();
if (reader12.HasRows)
{
reader12.Read();
locationrowID = reader12["ROW_ID"].ToString();
}
sqlConnection1.Close();
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM "+
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM "+
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND "+
"ACT.LOCATION_ID = '"+ locationrowID + "' AND ACT.MEMBER_ID = MEM.ROW_ID AND LOC.NAME = '"+ AdminsCurrentLocation + "'", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
What stumps me is that my other query is working fine for the case where TempLocationIdbox.Text == "Y"...
Thanks , any help would be much appreciated.
Instead of using if (reader.HasRows) you need to use while (reader.Read()).Also created some kind of collection for example List<T> and populate it with results inside the while loop.Then outside the loop set the DataSource of the GridView control to point to List<T>.Here's a complete example:
public class Activity
{
public int RowID { get; set; }
public DateTime Created { get; set; }
public string FirstName { get; set; }
}
public partial class UsingSqlDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.GetData();
}
}
private void GetData()
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
var activities = new List<Activity>();
using (var con = new SqlConnection(cs))
{
using(var cmd = new SqlCommand("SELECT ACT.ROW_ID,ACT.CREATED,ACT.FIRST_NAME FROM [dbo].[S_ACTIVITY] ACT", con))
{
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var activity = new Activity();
activity.RowID = Convert.ToInt32(reader["ROW_ID"]);
activity.Created = DateTime.Parse(reader["CREATED"].ToString());
activity.FirstName = Convert.ToString(reader["FIRST_NAME"]);
activities.Add(activity);
}
}
}
}
GridView1.DataSource = activities;
GridView1.DataBind();
}
}
Output:
A better solution would be to put your in-line query in a stored proc and execute the stored proc.
You could also bring it in a dataset and bind the gridview with that. but that is completely your choice.
In-line queries are very error prone and results could be unpredictable hence refrain using that.
I Planned to insert image in database. But there is some problem while inserting i.e (image format : input string was not in correct format). Please help me . Thanks in advance.
Error comes in this line -> int count = cmd.ExecuteNonQuery();
I have created the database with img (column name) Blob (datatype).
public partial class check1 : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void btnupload_Click(object sender, EventArgs e)
{
if (fileupload.HasFile)
{
int length = fileupload.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileupload.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
string imagename = imgname.Text;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO brand (imgname,img) VALUES (#imagename,#imagedata)", con);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Blob).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
con.Close();
if(count==1)
{
BindGridData();
imgname.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
private void BindGridData()
{
MySqlConnection con = new MySqlConnection("server=localhost; database=esample; uid=root;");
MySqlCommand command = new MySqlCommand("SELECT imgname,img,bid from brand", con);
MySqlDataAdapter daimages = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
}
Using a class named Player with the id, name and photo values.
public static bool createUser(Player player)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO tbuser (id,sName,lbFoto) VALUES (#id,#name,#foto)", dbConnection);
cmd.Parameters.AddWithValue("#id", player.id).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("#name", player.Name).DbType = DbType.String;
cmd.Parameters.AddWithValue("#foto", player.Image).DbType = DbType.Binary;
try
{
if (dbConnection.State == ConnectionState.Closed)
dbConnection.Open();
cmd.ExecuteNonQuery();
dbConnection.Close();
return true;
}
}
catch { }
finaly
{
if (dbConnection.State == ConnectionState.Open)
dbConnection.Close();
}
return false;
}
Then for retrieval the data:
public static Player loadUser(string ID)
{
var table = Select(dbConnection, "tbuser", "id = " + ID);
Player player = new Player();
foreach (DataRow row in table.Rows)
{
player.id = (int)row[0];
player.Name = row[1].ToString();
player.Image = (byte[])row[2];
return player;
}
return null;
}
The function Select. This is an extra ;)
public static DataTable Select(MySqlConnection con, string tableName, string expressionWhere)
{
string text = string.Format("SELECT * FROM {0} WHERE {1};", tableName, expressionWhere);
MySqlDataAdapter cmd = new MySqlDataAdapter(text, con);
DataTable table = new DataTable();
if (con.State == ConnectionState.Closed)
con.Open();
try
{
cmd.Fill(table);
}
catch (Exception){}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
return table;
}
Handler
public class Handler2 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string id = context.Request.QueryString["Id"];
string constr = System.Configuration.ConfigurationManager
.ConnectionStrings["EmployeeDatabase"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("GetImage", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpID", id);
//cmd.Parameters.AddWithValue("#Gender", ge);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
byte[] imageBytes = (byte[])dr.GetValue(0);
context.Response.BinaryWrite(imageBytes);
}
dr.Close();
con.Close();
}
User Control
public void BindGridviewData()
{
String empid1 = Name;
// String empid1 = Request.QueryString["MyText"];
int empid = int.Parse(empid1);
//int empid = 1500422;
string constr = System.Configuration.ConfigurationManager
.ConnectionStrings["EmployeeDatabase"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("GetEmployeeDetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpID", SqlDbType.Int, 0).Value = empid;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Label9.Text = dr[0].ToString();
Label2.Text = dr[1].ToString();
Label3.Text = dr[2].ToString();
Label4.Text = dr[3].ToString();
Label5.Text = dr[4].ToString();
Label6.Text = dr[5].ToString();
Label7.Text = dr[6].ToString();
Label8.Text = dr[7].ToString();
Image2.ImageUrl = "~/Handler2.ashx?Id=" + empid;
}
In the above program if we are not getting image in image control we need to display the text on button as "Add your Image" and if we have image we need to display it as "Update your Image"
I have used following ways which are not working:
Option 1
if (Image2.ImageUrl != null)
{
PageLinkButton.Text = "Upadte your Image";
}
else
{
PageLinkButton.Text = "Add your Image";
}
Option 2
WebClient client = new WebClient();
byte[] Value = client.DownloadData(Image2.ImageUrl);
if (Value != null)
{
PageLinkButton.Text = "Update your Image";
}
else
{
PageLinkButton.Text = "Add your Image";
}
You could have your generic handler return 404 status code if the image doesn't exist:
public void ProcessRequest(HttpContext context)
{
string id = context.Request.QueryString["Id"];
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["EmployeeDatabase"].ConnectionString;
using (var con = new SqlConnection(constr))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "GetImage";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpID", id);
using (var dr = cmd.ExecuteReader())
{
if (dr.Read())
{
// the image was found
byte[] imageBytes = (byte[])dr.GetValue(0);
// Don't forget to set the proper content type
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(imageBytes);
}
else
{
// no record found in the database => return 404
context.Response.StatusCode = 404;
}
}
}
}
and then on the client you could use a WebClient to test if the image exists:
var imageUrl = "~/Handler2.ashx?Id=" + empid;
var baseUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority));
var url = new Uri(baseUri, VirtualPathUtility.ToAbsolute(imageUrl));
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Head, url);
var response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
// the image exists:
PageLinkButton.Text = "Update your Image";
Image2.ImageUrl = imageUrl;
}
else
{
// the image does not exist:
PageLinkButton.Text = "Add your Image";
}
}