@Bioukh answer works in VS2019 and somewhat works in VS2022. However, the results of embedding the DataGridView control in my UserControl then adding and editing the Columns using the answer does not enable those Columns to migrate to another instance of the UserControl. For example: Copy/Paste the UserControl and all of the embedded DataGridView's columns disappear from the new copy.
To Work Around this issue I maintain my DataGridView instances as native and use a public DataGridView property in my UserControl with the binding and docking performed in the property setter. I then drop my_UserControl on my form, drop my_DataGridView on my form, and then set my_UserControl.DataGridView = my_DataGridView. This work around preserves the native properties and behaviors associated with the DataGridView.
In my_UserControl, I have a Panel named "GridPanel" and a VScrollBar. I then added the following property:
///<summary>
/// Associates a native DataGridView with this UserControl
/// then sets the DataGridView.Parent to the Panel in this UserControl
/// and sets the DataGridView.Dock to Fill the Panel
///</summary>
public DataGridView? ContainedDataGridView
{
get
{
try
{
// if we have a DataGridView in our Panel then return it
if ((this.GridPanel.Controls.Count == 1)
&& (this.GridPanel.Controls[0] is DataGridView view))
{
return view;
}
}
catch (Exception ex)
{
//// TODO Handle "ContainedDataGridView get error"
}
// Return null if there is no DataGridView or there was an error checking for it.
return null;
}
set
{
try
{
// Clear the panel to prevent adding more than one DataGridView
this.GridPanel.Controls.Clear();
if (value is not null)
{
this.GridPanel.Controls.Add(value);
value.Parent = this.GridPanel;
value.Dock = DockStyle.Fill;
}
// else the panel remains cleared
}
catch (Exception ex)
{
//// TODO Handle "ContainedDataGridView set error"
}
}
}
The above snippet is coded as C# 10, .NET 6, Windows Forms App, UserControl and tested in Visual Studio 2022 version 17.0.3
MyDataGridColumns
. – Chaperone