I got a table 'IMAGES' with fields 'img_username' , 'img_image_path. From my form I can upload image path to database and copy the image to a specific folder. Now I want to show the image in a pictureboxaccording the username I am giving. I will share the code so far iwritten. Please help. Now am getting error when I try to show image by giving a username.
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in System.Drawing.dll... This is the error showing at
line 49. Is there any better way to do it?
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.IO;
-
- namespace ImageSaving
- {
- public partial class Form1 : Form
- {
- SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings.Get("connectionstring").ToString());
- string displayimg, filepath;
- string folderpath = @"D:\Images\";
- OpenFileDialog open = new OpenFileDialog();
- SqlCommand cmd;
- public Form1()
- {
- InitializeComponent();
- }
-
-
-
-
- private void btn_ShowImage_Click(object sender, EventArgs e)
- {
- string sql = "select * from images where img_username=@username";
-
- SqlCommand cmdrtrv = new SqlCommand(sql, con);
- cmdrtrv.Parameters.AddWithValue("@username", txt_UserName.Text);
-
- try
- {
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- using (SqlDataReader reader = cmdrtrv.ExecuteReader())
- {
- if (reader.Read())
- {
- string path = @reader["img_path"].ToString();
- pctbx_UserImage.Image = Image.FromFile("" + reader["path"].ToString());
- }
- }
-
- }
- finally
- {
- con.Close();
- }
-
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- con.Open();
-
- }
-
-
- private void btn_SearchImage_Click(object sender, EventArgs e)
- {
- open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp|all files|*.*";
- if(open.ShowDialog()==DialogResult.OK)
- {
- displayimg = open.SafeFileName;
- txt_ImagePath.Text = open.FileName;
-
- pctbx_UserImage.Image = new Bitmap(open.FileName);
- filepath = open.FileName;
- }
- }
-
-
-
- private void btn_Upload_Click(object sender, EventArgs e)
- {
- if(filepath=="")
- {
- cmd.Parameters.AddWithValue("@Path", "");
- }
- else
- {
-
- cmd = new SqlCommand("insert into images values(@UserName,@Path)",con);
- cmd.CommandType = CommandType.Text;
- cmd.Parameters.AddWithValue("@UserName", txt_UserName.Text);
- cmd.Parameters.AddWithValue("@Path", folderpath+Path.GetFileName(open.FileName));
- File.Copy(filepath, Path.Combine(folderpath, Path.GetFileName(open.FileName)),true);
- if(con.State==ConnectionState.Closed)
- {
- con.Open();
- }
- cmd.ExecuteNonQuery();
- MessageBox.Show("Image Saved");
- con.Close();
- }
- }
- }
- }