New to Telerik UI for WinForms? Download free 30-day trial

How to Copy the Image in a GridView's Cell

Environment

Product Version Product Author
2021.2.511 RadGridView Desislava Yordanova

Description

The copy functionality, that RadGridView offers, supports three formats: Text, HTML, CommaSeparatedValue. The internal copy implementation uses the Clipboard.SetDataObject method where the cell's content is extracted in the supported formats. If you store Bitmap values in the cells from the GridViewImageColumn, this value is stored as "System.Drawing.Bitmap" which is the string representation of the type stored in the cell's Value.

This article demonstrates how to achieve copy image functionality in RadGridView and thus to be able to paste it to another application, e.g. MS Excel:

copy-image-in-grid-cells 001

Solution

This requires implementing additional functionality and overriding the default Copy method logic. The Clipboard.SetImage method is suitable for this case as it clears the Clipboard and then adds an Image in the Bitmap format.

public RadForm1()
{
    InitializeComponent();
    GridViewImageColumn imageColumn = new GridViewImageColumn();
    this.radGridView1.Columns.Add(imageColumn);
    GridViewTextBoxColumn textColumn = new GridViewTextBoxColumn();
    this.radGridView1.Columns.Add(textColumn);

    this.radGridView1.Rows.Add(Properties.Resources.calendar, Guid.NewGuid().ToString());
    this.radGridView1.Rows.Add(Properties.Resources.Clock_Alarm, Guid.NewGuid().ToString());

    this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
    this.radGridView1.ClipboardCopyMode = GridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
}

public class CustomGrid : RadGridView
{
    protected override RadGridViewElement CreateGridViewElement()
    {
        return new CustomRadGridViewElement();
    }

    public override string ThemeClassName
    {
        get
        {
            return typeof(RadGridView).FullName;
        }
    }
}

public class CustomRadGridViewElement : RadGridViewElement
{
    protected override MasterGridViewTemplate CreateTemplate()
    {
        return new CustomMasterGridViewTemplate();
    }

    protected override Type ThemeEffectiveType
    {
        get
        {
            return typeof(RadGridViewElement);
        }
    }
}

public class CustomMasterGridViewTemplate : MasterGridViewTemplate
{
    public override void Copy()
    {
        Bitmap imageValue = this.CurrentRow.Cells[this.CurrentColumn.Name].Value as Bitmap;
        if (imageValue != null && this.CurrentColumn is GridViewImageColumn)
        {
            Clipboard.SetImage(imageValue);
        }
        else
        {
            base.Copy();
        }
    }
}   

Do not forget to replace the default RadGridView with the custom class (CustomGrid) in the InitializeComponent method.