Search code examples
c#datagridviewcolumndatagridviewlinkcolumn

c# DataGridViewLinkColumn have cell value as image instead of text (Clickable/Linkable Image)


Is is possible to have a image instead of text in the DataGridViewLinkColumn. In the below example, instead of "search" text, can we have a search icon in the cell!?

    private void Form1_Load(object sender, EventArgs e)
    {
        DataGridViewLinkColumn c = new DataGridViewLinkColumn();
        dataGridView1.Columns.Add(c);
        dataGridView1.Rows.Add();
        dataGridView1.Rows[0].Cells[0].Value = "search";
    }

When I try assigning a image to the value of the cell, it is not getting displayed rather displayed as "System.Drawing.Bitmap"


Solution

  • Use a standard DataGridViewImageColumn to display the images, then create a DataGridView_CellMouseMove event for the DataGridView with the following code

        private void DataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == DataGridViewImageColumn1.Index)
            {
                Cursor = Cursors.Hand;
            }
            else
            {
                Cursor = Cursors.Default;
            }
        }
    

    Add logic to detect rows if required.

    The DataGridView_CellMouseClick events will still be needed for your links.

    And you may also need a DataGridView_MouseLeave event to ensure that you set the Cursor back to the default.