I am new at programming and I'm trying to upload an image and save it in folder with the current product id. However when I update the image a new folder is created. Instead of return maxId++, how can I store the ID in DataContext and return that if it exists? Here goes the code.
private void upload_Click_1(object sender, EventArgs e)
{
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select image for this product";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (opFile.ShowDialog() == DialogResult.OK)
{
try
{
string iName = opFile.FileName;
var dir = @"images/" + GetCurrentId();
var path = Path.Combine(dir, Path.GetFileName(iName));
if (!Directory.Exists(dir) &&(produto)this.tbprodutoBindingSource.Current == null))
{
Directory.CreateDirectory(dir);
}
File.Copy(iName, path);
}
catch (Exception ex)
{
MessageBox.Show("Unable to open file " + ex.Message);
}
}
else
{
opFile.Dispose();
}
}
private int GetCurrentId()
{
var result = dataContextFactory.DataContext.produtos.Max(x => x.id_produto);
int maxId = Convert.ToInt32(result);
if (maxId == 0) maxId = 1;
else
maxId++;
return maxId;
}