How to Deal with Invalid FORMATETC structure Error when Copying Data from RadGridView
Environment
| Product Version | Product | Author |
|---|---|---|
| 2022.3.913 | RadGridView for WinForms | Desislava Yordanova |
Description
When the user performs a Copy operation in RadGridView either with Ctrl + C or via the context menu option, it is possible to observe the following error:
System.Runtime.InteropServices.COMException occurred Message: Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Windows.Forms.dll Additional information: Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))
This tutorial gives more details about the error and how it may be prevented.
Solution
This error doesn't seem to be related directly to the RadGridView control from the Telerik UI for WinForms suite. When a Copy operation is performed, RadGridView internally uses Clipboard.SetDataObject(Object) method. In different general programming forums, it is confirmed that if the SetDataObject(Object, Boolean) method overload is used, the error doesn't occur anymore.
The following sample code snippet demonstrates how to customize the copy behavior in RadGridView:
public class CustomGrid : RadGridView
{
public override string ThemeClassName
{
get
{
return typeof(RadGridView).FullName;
}
}
protected override RadGridViewElement CreateGridViewElement()
{
return new CustomRadGridViewElement();
}
}
public class CustomRadGridViewElement : RadGridViewElement
{
protected override Type ThemeEffectiveType
{
get
{
return typeof(RadGridViewElement);
}
}
protected override MasterGridViewTemplate CreateTemplate()
{
return new CustomMasterGridViewTemplate();
}
}
public class CustomMasterGridViewTemplate : MasterGridViewTemplate
{
public override void Copy()
{
MethodInfo mi = typeof(MasterGridViewTemplate).GetMethod("CopyContent", BindingFlags.Instance | BindingFlags.NonPublic);
object copyResult = mi.Invoke(this, new object[] { false });
Clipboard.SetDataObject(copyResult, true);
}
}