How can I retrieve image into picture box using image path in database? Before this I retrieve from shared folder but its make my system slow when loading image. Then I changes the method wheres I want to retrieve image into picture box using image path that stored in MSSQL database. Hopefully it not slow down my system. Anyone please help me. Here is my code but not work to retrieve image.
private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxEmplNo.Text != "")
{
string selectSql = "select a.name, a.empno, a.workno, a.icnum, a.passport, a.deptno, a.section, a.designation, b.path from m_employee a inner join m_emp_photo b on b.empno=a.empno where a.empno= #empno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#empno", textBoxEmplNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxWorkNo.Text = (read["workno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
textBoxDesignation.Text = (read["designation"].ToString());
pictureBox1.Image = Image.FromFile("#path");
}
}
pictureBox1.Image = Image.FromFile("" + read["path"].ToString());
pictureBox1.SizeMode=System.Windows.Forms.PictureBoxSizeMode.StretchImage;
Related
I'm new here and I've also searched about my problem, but I could manage to solve it.
I would like to save and retrieve images to/from Database(SQL) in C# WPF.
I have to make a project about storing a recipe. A recipe contains a table in the Database with the columns: Id, Name, Image, Content.The Information has to be saved and then the name of the recipe(currently done) and images(here is the problem) has to be displayed in a Grid, (so far i don't need to work with the "content" column from the database. That comes later).
I think that I have succeeded in the saving of image to the database, but I am not completely sure. If the saving of the image to the DB is correct, I need a function to retrieve it.
I would be happy for some help. Many Thanks!
D.Tsvet
Thats a sample of the future end result. The image has to be under the name
// Add recipe Window
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public partial class add_Recipe : Window
{
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public add_Recipe()
{
InitializeComponent();
}
// Upload a picture from your device
private void browseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
FileName = op.FileName.ToString();
image_box.Source = new BitmapImage(new Uri(op.FileName));
}
string dbConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\guiProjekte\Stands\Projekt_GUI_200418\Projekt_GUI_20042018\Projekt_GUI_160418\Projekt_GUI\1234\1234\Database.mdf;Integrated Security=True;";
private void saveRecipe_Button(object sender, RoutedEventArgs e)
{
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string q = "insert into recipes(Name,Image,Content)values('" + textBox_newRecipe.Text.ToString() + "','" + ImageData + "','" + content_box.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Connection made Successfuly..!");
this.Close();
myRecipes_Window obj_myRecipes_Window = new myRecipes_Window();
obj_myRecipes_Window.Show();
//Retrieve Recipe Window:
public void FillRecipes()
{
int column = 0;
int row = 0;
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
String sqlSelectQuery = "SELECT * FROM recipes";
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(column < 3)
{
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
else
{
column = 0;
row++;
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
}
}
I made some changes about my post. I'm sorry for the previous unclearness.
I'm a newbie in C# programming language. I have problem on how can I check either the image is exist or not in database? I'm using database inner join. My current code is work. But if the image not exist in database, all the text box does not get value from database.I don't want like that. I want like this > if image not exist, all the text box got their value from database, even though image not exist. Please somebody help me. Here is my code:
private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxEmplNo.Text != "")
{
string selectSql = "select a.name, a.empno, a.workno, a.icnum, a.passport, a.deptno, a.section, a.designation, b.path from m_employee a inner join m_emp_photo b on b.empno=a.empno where a.empno= #empno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#empno", textBoxEmplNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxWorkNo.Text = (read["workno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
textBoxDesignation.Text = (read["designation"].ToString());
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile("" + read["path"].ToString());
dataGridView1.Visible = false;
}
}
if (!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxWorkNo.Text = "";
textBoxName.Text = "";
}
dataGridView1.Visible = false;
}
}
From my understanding you want to show employee data irrespective of his photo present of not in database so do the left join on tables so your query changes as below,
select a.name, a.empno, a.workno, a.icnum, a.passport, a.deptno, a.section, a.designation, b.path
from
m_employee a left join m_emp_photo b
on b.empno=a.empno
where
a.empno= #empno
This will give you all records for given employee number from left side table and matching from right side if no values available then NULL for that row from right side table.
Although you need to handle the NULL value for b.Path in the code.
so in code before this code line,
pictureBox1.Image = Image.FromFile("" + read["path"].ToString());
check if path is DBNULL or not by comparing with System.DBNull.Value.
I have problem regarding passing the selected cell from datagridview to textbox. The problem is when I select the cell in gridview, it shows error at the code that I already **. I already check all the possible error such as spelling, column have in gridview but still cannot detect wheres the error. Please anyone help me. Here is my code:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
textBoxName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
**textBoxEmplNo.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();**
**textBoxWorkNo.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();**
string selectSql = "select icnum, passport, deptno, section from m_employee where workno=#workno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#workno", textBoxWorkNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
string imgFilePath = #"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\EV\Images\photo\" + textBoxEmplNo.Text + ".jpg";
if (File.Exists(imgFilePath))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
// MessageBox.Show("No Image Found");
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(#"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\EV\Images\photo\No-image-found.jpg");
}
}
}
}
finally
{
con.Close();
}
dataGridView1.Visible = false;
}
I have created a table in which there is one column of type varbinary(max) to store the files.
What I want to do is that I want to show a pictureBox if that column is not null nad I have written this code:
private void ViewSentMailDet_Load(object sender, EventArgs e)
{
picturebox.Visible = false;
string con_string = #"Data Source=(local);Initial Catalog=fyp;Integrated Security=true";
SqlConnection con = new SqlConnection(con_string);
string qry = "select file from sentmail where msg_id='"+id of a particular row+"'";
SqlDataAdapter ad = new SqlDataAdapter(qry, con);
DataTable dt = new DataTable();
ad.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
if (dr["file"] != null)
picturebox.Visible = true;
}
}
But still its showing the pictureBox on load event of this page even if the file column is null.
Furthermore I want to download this particular file from the table to a disc when the user clicks on the pictureBox.
One of the major rules of using any kind of database is never return data you don't need. With this in mind you should exclude rows with no image using the query rather than checking after the fact.
So:
"select file from sentmail where msg_id='"+id of a particular row+"' and file is not null"
Rather than:
if (dr["file"] != DBNull.Value)
{
picturebox.Visible = true;
}
Giving us:
private void ViewSentMailDet_Load(object sender, EventArgs e)
{
picturebox.Visible = false;
string con_string = #"Data Source=(local);Initial Catalog=fyp;Integrated Security=true";
SqlConnection con = new SqlConnection(con_string);
string qry = "select file from sentmail where msg_id='"+id of a particular row+"' and file is not null";
SqlDataAdapter ad = new SqlDataAdapter(qry, con);
DataTable dt = new DataTable();
ad.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
using (var ms = new MemoryStream((byte[])dr["file"]))
picturebox.Image = Image.FromStream(ms);
picturebox.Visible = true;
}
}
if (dr["file"] != DBNull.Value)
{
picturebox.Visible = true;
}
To check if the column contains binary data or null, you can use
if(!dr.IsNull("attach"))
{
attachment.Visible = true;
}
Get image bytes
Byte[] bytes = (Byte[])dr["attach"];
Convert image bytes to image
Image image = null;
using (var ms = new MemoryStream(bytes))
image = Image.FromStream(ms);
Show the picture on the picturebox
picturebox.Image = image;
To save the image, on picturebox.Click event handler
picturebox.Image.Save(#"drive:/path/to/save/image.bmp");
Glad to help! Please remember to accept the answer if you found it helpful.
I am using asp.net with c# to build website, but now i come into a problem. I insert image with blob type into mysql database but i cannot retrieve it. There is no picturebox layout for web controls. I want to use image.imageURL to display this image. I searched a lot, some recommend use another aspx page, some recommend using ashx, but i cannot find a detailed solution. Here is what i have now:
protected void Button1_Click(object sender, EventArgs e)
{
String myname = Request.QueryString["Name"];
string myConnection = "server=127.0.0.1;uid=root;" + "pwd=81210ZLK;database=database;" + "Allow User Variables=True";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.ConnectionString = myConnection;
MySqlCommand SelectCommand = new MySqlCommand();
string mySQL = "SELECT iddb1,fullname,age,gender,healthrecord,headpicture FROM database.db1 where fullname = #myname ";
SelectCommand.CommandText = mySQL;
SelectCommand.Parameters.AddWithValue("#myname", myname);
SelectCommand.Connection = myConn;
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
Int16 ID = myReader.GetInt16(0);
string FName = myReader.GetString(1);
Int16 FAge = myReader.GetInt16(2);
string FGender = myReader.GetString(3);
string FRecord = myReader.GetString(4);
ShowID.Text = ID.ToString();
ShowName.Text = FName.ToString();
ShowAge.Text = FAge.ToString();
ShowGender.Text = FGender.ToString();
ShowRecord.Text = FRecord.ToString();
byte[] imgg = (byte[])(myReader["headpicture"]);
if (imgg == null)
Image1.ImageUrl = null;
else {
MemoryStream mstream = new MemoryStream(imgg);
// Image1.ImageURL = System.Drawing.Image.FromStream(mstream);
}
}
myConn.Close();
}
catch (Exception ex)
{
MessageBoxShow(this, ex.Message);
}
}
Here come with the problem and i marked it with \\
Try this ,
Image1.ImageURL = "data:image/jpeg;base64,"+Convert.ToBase64String(imgg);