The problem is in this line:
if (dataViewImages.SelectedRows.Count == 1 && dataViewImages.SelectedCells[0].ColumnIndex == 1 && dataViewImages.SelectedCells[0].Value != null)
dataViewImages.SelectedRows.Count == 1
and dataViewImages.SelectedCells[0].ColumnIndex == 1
cannot be satisfied at the same time.
If dataViewImages.SelectedRows.Count == 1 is true, you must select the row, then dataViewImages.SelectedCells[0].ColumnIndex must be 0.
If you select a cell, then dataViewImages.SelectedRows.Count must be 0.
In addition, I checked your DownloadAttachment method, it has some problems.
-
string fileName = Convert.ToString(dgvCell.Value);
The result will beSystem.Drawing.Bitmap
, the type of the object instead of the path, you cannot get a correct FileInfo based on it. Try to convert it to Image and add a method to get its extension.Image image = (Image)dgvCell.Value; string fileExtension = GetImageType(image); public string GetImageType(Image image) { if (image.RawFormat.Equals(ImageFormat.Bmp)) { return "Bmp"; } else if (image.RawFormat.Equals(ImageFormat.MemoryBmp)) { return "BMP"; } else if (image.RawFormat.Equals(ImageFormat.Wmf)) { return "Emf"; } else if (image.RawFormat.Equals(ImageFormat.Wmf)) { return "Wmf"; } else if (image.RawFormat.Equals(ImageFormat.Gif)) { return "Gif"; } else if (image.RawFormat.Equals(ImageFormat.Jpeg)) { return "Jpeg"; } else if (image.RawFormat.Equals(ImageFormat.Png)) { return "Png"; } else if (image.RawFormat.Equals(ImageFormat.Tiff)) { return "Tiff"; } else if (image.RawFormat.Equals(ImageFormat.Exif)) { return "Exif"; } else if (image.RawFormat.Equals(ImageFormat.Icon)) { return "Ico"; } return "Not an image."; }
-
byteData = myAttachments[dgvCell.RowIndex];
In the current code you provided, myAttachments is not initialized, and no value is added to it anywhere. I am not very clear about its usefulness, so I do not use it in my current code.private void DownloadAttachment(DataGridViewCell dgvCell) { Image image = (Image)dgvCell.Value; string fileExtension = GetImageType(image); //show save as dialog using (SaveFileDialog saveFileDialog1 = new SaveFileDialog()) { //Set Save dialog properties saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension; saveFileDialog1.Title = "Save File as"; saveFileDialog1.CheckPathExists = true; saveFileDialog1.FileName = "1."+fileExtension; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { image.Save(saveFileDialog1.FileName); } } }
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.