Search code examples
c#imagedatagridviewdatagridviewimagecolumn

How to add more than one image to DataGridViewImageColoumn and add event to each image in windows forms


I need to add more than one images (three images) to Data Grid View's images column, but the default image column doesn't allow me to set more than one image. And I need to attach a separate event to each image.
As I am new at programming please help me out. Thanks!
Here's my code to add image column to Data Grid View and initialize the image coloumn:

DataGridViewImageColumn dgColMemos = new DataGridViewImageColumn();

Columns Initilization ( i have not include whole code):

this.dgPartslist[sColName, iRowIndex].Value = (Image)Properties.Resources.Memo_Image; 

Solution

  • The most flexible solution for storing data in a place that doesn't allow storing many items but does offer a Tag is to create a suitable class:

    class ImagesTag
    {
        public Image Img1 { get; set; }
        public Image Img2 { get; set; }
        public Image Img3 { get; set; }
        public int CurrentImg { get; set; }
    
        public ImagesTag(Image i1, Image i2, Image i3)
        { CurrentImg = 0; Img1 = i1; Img2 = i2; Img3 = i3; }
    }
    

    Now you can add an instance to each ImageCell's Tag in addition to setting the image itself; here I set up 3 rows:

    DataGridViewImageColumn dgColMemos = new DataGridViewImageColumn();
    
    dataGridView1.Columns.Add(dgColMemos);
    dataGridView1.RowCount = 3;
    
    for (Int16 r = 0; r < dataGridView1.RowCount; r++)
    {
        ImagesTag I3 = new ImagesTag(imageList2.Images[r * 3], 
                       imageList2.Images[r * 3 + 1], imageList2.Images[r * 3 + 2]);
        dataGridView1[0, r].Value = I3.Img1;
        dataGridView1[0, r].Tag = I3;
    }
    

    Note that I don't access resources but an ImageList for my tests. Your setup code will differ greatly!

    I set the first Image to display and put this index in the class as well. This is because it is hard or maybe even impossible without examining the pixels to find out just which image is currently displayed.

    Here is an example of rotating through the three Images on a MouseClick:

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      ImagesTag I3 = (ImagesTag)(dataGridView1[e.ColumnIndex, e.RowIndex].Tag);
      int current = (int)(I3.CurrentImg);
      int next = ++current % 3;
      dataGridView1[0, e.RowIndex].Value = next == 0 ? I3.Img1 : next == 1 ? I3.Img2 : I3.Img3;
      I3.CurrentImg = next;
      dataGridView1[0, e.RowIndex].Tag = I3;
    }
    

    Of course you are free to adapt the design of the class to your needs; you could replace the 3 hard coded images by a List<Image>, you could add events/delegates to call when one is clicked, add texts to display as tooltips and so on..