I have a program that allows the user to upload pictures on their pets. You can then upload 5 different images, and all these images are saved in a specific folder. Then the path itself is saved in the database.
First, press "combobox" and in this list you will find all the pets you have entered into the program. Then select "Load image". This image will then be saved in a folder and path in the database. But if you upload one more image, with the same pet. This image will also be saved in the same folder. What I want to do is delete the previous image and then update the database with the new path. Well, I hope you understand what I need.
private void btn_upload_Click(object sender, EventArgs e) //Load image
{
if (string.IsNullOrEmpty(combo_dogname.Text) || string.IsNullOrWhiteSpace(combo_dogname.Text))
{
MessageBox.Show("Du måste välja en hund!");
}
else
{
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Välj en bild";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
string appPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\UserImages\";
if (Directory.Exists(appPath) == false)
{
Directory.CreateDirectory(appPath);
}
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.SafeFileName; // <---
string filepath = opFile.FileName; // <---
File.Copy(filepath, appPath + iName); // <---
pbox_jordbruksverket.Image = new Bitmap(opFile.OpenFile());
path = filepath;
name = iName;
saveContent();
}
catch
{
if (File.Exists(appPath))
{
File.Delete(appPath);
MessageBox.Show("Filen finns redan!");
}
}
}
else
{
opFile.Dispose();
}
}
}
//Strings
public static string path;
public static string name;
//Save content after uploading image.
public void saveContent()
{
con.Open();
SqlCommand Rem = con.CreateCommand();
Rem.CommandType = CommandType.Text;
string sqlAdd = "INSERT INTO lexidatabase.dbo.tbl_jordbruksverket (username, dogname, img) values('" + Login.username + "', '" + combo_dogname.Text + "', '" + path + "')";
SqlCommand cmd = new SqlCommand(sqlAdd, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Bild sparad");
con.Close();
}
//Removing all images from the selected pet.
private void btn_removeImg_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(combo_dogname.Text) || string.IsNullOrWhiteSpace(combo_dogname.Text))
{
MessageBox.Show("Du måste välja hund först!");
}
else
{
con.Open();
SqlCommand remove = con.CreateCommand();
remove.CommandType = CommandType.Text;
string sqlRemove = "DELETE FROM lexidatabase.dbo.tbl_jordbruksverket WHERE username = '" + Login.username + "' AND dogname = '" + combo_dogname.Text + "'";
SqlCommand cmd = new SqlCommand(sqlRemove, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Bild borttagen!");
con.Close();
}
}