question

Manchi-0330 avatar image
0 Votes"
Manchi-0330 asked TimonYang-MSFT answered

Help out with this code please. Image from datagridview to desktop

i am displaying images into datagridview, is working fine without any problem, but when i wan to download a single image it keeps on showing me problems that i have to (Select a single cell from Attachment column). Please the code is detailed. one can try it and help out with a solution. thank you using


 using System;
 using System.Collections.Generic;
 using System.Drawing;
 using System.IO;
 using System.Windows.Forms;
    
 namespace ImageThumbnailDataGridView
 {
     public partial class FormMain : Form
     {
         private List<string> files = null;
         private int numberPreviewImages = 100;
         private int imageSize = 90;
         private int currentStartImageIndex = 0;
         private int currentEndImageIndex = 0;
    
         //Dictionary will store the attachments
         Dictionary<int, byte[]> myAttachments;
    
         public FormMain()
         {
             InitializeComponent();
         }
    
         private void btnLoadImages_Click(object sender, EventArgs e)
         {
             if (openFileDialog.ShowDialog(this) != DialogResult.OK)
             {
                 return;
             }
    
             files = new List<string>();
             files.AddRange(openFileDialog.FileNames);
             files.Sort();
    
             if (numberPreviewImages == 1)
             {
                 currentStartImageIndex = 0;
                 currentEndImageIndex = 1;
             }
             else
             {
                 currentEndImageIndex = currentStartImageIndex + numberPreviewImages - 1;
             }
    
             this.LoadImages();
         }
    
         private void LoadImages()
         {
             try
             {
                 if (files == null)
                 {
                     return;
                 }
    
                 if (this.WindowState == FormWindowState.Minimized)
                 {
                     return;
                 }
    
                 dataViewImages.Rows.Clear();
                 dataViewImages.Columns.Clear();
    
                 int numColumnsForWidth = (dataViewImages.Width - 10) / (imageSize + 20);
                 int numRows = 0;
    
                 int numImagesRequired = 0;
    
                 if (currentEndImageIndex > files.Count)
                 {
                     // Are we requesting to display more images than we actually have? If so then reduce
                     if (currentStartImageIndex == 0)
                     {
                         numImagesRequired = files.Count;
                     }
                     else
                     {
                         numImagesRequired = (currentEndImageIndex - currentStartImageIndex) - (currentEndImageIndex - _files.Count);
                     }
                 }
                 else
                 {
                     // Calculated the number of rows we will need for normal use
                     numImagesRequired = currentEndImageIndex - currentStartImageIndex; 
                 }
    
                 numRows = numImagesRequired / numColumnsForWidth;
    
                 if (numImagesRequired % numColumnsForWidth > 0)
                 {
                     numRows += 1;
                 }
    
                 if (numImagesRequired < numColumnsForWidth)
                 {
                     numColumnsForWidth = numImagesRequired;
                 }
    
                 int numGeneratedCells = numRows * numColumnsForWidth;
    
                 // Dynamically creating the columns
                 for (int index = 0; index < numColumnsForWidth; index++)
                 {
                     DataGridViewImageColumn dataGridViewColumn = new DataGridViewImageColumn();
    
                     dataViewImages.Columns.Add(dataGridViewColumn);
                     dataViewImages.Columns[index].Width = imageSize + 20;
                 }
    
                 // Creating the rows
                 for (int index = 0; index < numRows; index++)
                 {
                     dataViewImages.Rows.Add();
                     dataViewImages.Rows[index].Height = imageSize + 20;
                 }
    
                 int columnIndex = 0;
                 int rowIndex = 0;
    
                 for (int index = currentStartImageIndex; index < currentStartImageIndex + numImagesRequired; index++)
                 {
                     // Load the image from the file and add to the DataGridView
                     Image image = Helper.ResizeImage(files[index], imageSize, imageSize, false);
                     dataViewImages.Rows[rowIndex].Cells[columnIndex].Value = image;
                     dataViewImages.Rows[rowIndex].Cells[columnIndex].ToolTipText = Path.GetFileName(files[index]);
    
                     // Have we reached the end column? if so then start on the next row
                     if (columnIndex == numColumnsForWidth - 1)
                     {
                         rowIndex++;
                         columnIndex = 0;
                     }
                     else
                     {
                         columnIndex++;
                     }
                 }
    
                 // Blank the unused cells
                 if (numGeneratedCells > numImagesRequired)
                 {
                     for (int index = 0; index < numGeneratedCells - numImagesRequired; index++)
                     {
                         DataGridViewCellStyle dataGridViewCellStyle = new DataGridViewCellStyle();
                         dataGridViewCellStyle.NullValue = null;
                         dataGridViewCellStyle.Tag = "BLANK";
                         dataViewImages.Rows[rowIndex].Cells[columnIndex + index].Style = dataGridViewCellStyle;
                     }
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
         }
    
         private void dataViewImages_Resize(object sender, EventArgs e)
         {
             this.LoadImages();
         }
    
         private void FormMain_Load(object sender, EventArgs e)
         {
             imageSize = 90;
         }
    
         private void button1_Click(object sender, EventArgs e)
         {
             if (dataViewImages.SelectedRows.Count == 1 && dataViewImages.SelectedCells[0].ColumnIndex == 1 && dataViewImages.SelectedCells[0].Value != null)
             {
                 DownloadAttachment(dataViewImages.SelectedCells[0]);
             }
             else
                 MessageBox.Show("Select a single cell from Attachment column", "Error uploading file", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         private void DownloadAttachment(DataGridViewCell dgvCell)
         {
             string fileName = Convert.ToString(dgvCell.Value);
    
             //Return if the cell is empty
             if (fileName == string.Empty)
                 return;
    
             FileInfo fileInfo = new FileInfo(fileName);
             string fileExtension = fileInfo.Extension;
    
             byte[] byteData = null;
    
             //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 = fileName;
    
                 if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                 {
                     byteData = myAttachments[dgvCell.RowIndex];
                     File.WriteAllBytes(saveFileDialog1.FileName, byteData);
                 }
             }
         }
     }
 }
dotnet-csharp
· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

If you were to place your project in a GitHub repository and provide the link that would be a start for us to assist. If you have never used GitHub, now is a great time to learn as it's easy to do inside of VS2019.

1 Vote 1 ·

Please guide me on how to create a GitHub account

0 Votes 0 ·

Doing that now

1 Vote 1 ·

You created a repository with a readme, not what I asked for. See the following instructions. I don't have a simple repository to show so the one below will have to do. Each folder is a C# project created in VS2019.

82117-f1.png


0 Votes 0 ·
f1.png (71.3 KiB)

1 Answer

TimonYang-MSFT avatar image
1 Vote"
TimonYang-MSFT answered

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.

  1. string fileName = Convert.ToString(dgvCell.Value);

    The result will be System.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.";
             }
    
  2. 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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.