0

I am trying to make event viewer using datagridview in c#

This is my target

I am already read many source, and still confused to implement it.

Source add custom DataGridViewColumn with label and button per cell How to add a Label to a DataGridView cell

Big thanks for the helps

Cak Dham
  • 1
  • 1

1 Answers1

0

The following shows how to read images from files, place them into a Dictionary then load them into rows in a DataTable, of course for a real app there are more images and logic to assign the images dependent on your logic.

Note that the image cells can not be selected.

The alternative is to create a custom DataGridViewColumn or the following solution.

enter image description here

Backend mockup

using System.Data;

namespace DataGridViewImages.Classes
{
    internal class Operations
    {
        public static Dictionary<int, byte[]> SmallImages()
        {
            Dictionary<int, byte[]> dictionary = new Dictionary<int, byte[]>
            {
                { 1, File.ReadAllBytes("blueInformation_16.png") },
                { 2, File.ReadAllBytes("radiobutton16.png") }
            };

            return dictionary;
        }

        public static DataTable Table()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("image", typeof(byte[]));
            dt.Columns.Add("text", typeof(string));

            var images = SmallImages();

            dt.Rows.Add(images[1], "Some text");
            dt.Rows.Add(images[2], "More text");

            return dt;
        }
    }
}

Form code

using DataGridViewImages.Classes;

namespace DataGridViewImages
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            Shown += OnShown;
            dataGridView1.SelectionChanged += DataGridView1OnSelectionChanged;
            dataGridView1.RowHeadersVisible = false;
        }

        private void DataGridView1OnSelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentCell.ColumnIndex == 0)
            {
                dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex]
                    .Cells[0].Selected = false;
            }
        }

        private void OnShown(object sender, EventArgs e)
        {
            dataGridView1.DataSource = Operations.Table();
            dataGridView1.Columns[0].HeaderText = "";
            dataGridView1.Columns[0].Width = 25;
        }
    }
}
Karen Payne
  • 4,341
  • 2
  • 14
  • 31
  • thanks... i wonder if we could use original property from label control. Because label can also contain property of the image. But your solutions is what i need, Thanks so much – Cak Dham Sep 27 '22 at 05:23