0

I created a DataGridView and set its properties as I wanted.
Problem is that I can have four same-look DataGridView in application , depending on some conditions in my app. I want to know if I could create one instance of DataGridView programmatically and copy all properties from the original DataGridView, so that I have 2,3,4 same DataGridViews?

I know that it is possible via the designer but how to copy it programatically?


I heard about extension methods but is there some easier approach?


EDIT: i added new method:

private void copyControl(Control sourceControl, Control targetControl)
    {
        // make sure these are the same
        if (sourceControl.GetType() != targetControl.GetType())
        {
            throw new Exception("Incorrect control types");
        }

        foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties())
        {
            object newValue = sourceProperty.GetValue(sourceControl, null);

            MethodInfo mi = sourceProperty.GetSetMethod(true);
            if (mi != null)
            {
                sourceProperty.SetValue(targetControl, newValue, null);
            }
        }
    }



   DataGridView dgw = new DataGridView();
   copyControl(PartsDgv, dgw);


And i get this exception
enter image description here

Flo Rida
  • 55
  • 6
  • 1
    Possible duplicate of [It is possible to copy all the properties of a certain control? (C# window forms)](https://stackoverflow.com/questions/3473597/it-is-possible-to-copy-all-the-properties-of-a-certain-control-c-window-forms) – Mike Lowery Aug 30 '18 at 18:04
  • Thanks @MikeLowery i had same idea but i didnt know about Property info, thanks! – Flo Rida Aug 30 '18 at 18:09
  • @MikeLowery i still get an exception, check my edited post – Flo Rida Aug 30 '18 at 21:32
  • Think your problem is cells are properties of a datagridview and your trying to straight move them from one datagridview to another. You will need to create new copies of the cells for sourceControls. – Hursey Aug 30 '18 at 22:27
  • 1
    A better approach might be to create a user control with a datagridview on it and all your standard properties set, then add that to your forms. – Hursey Aug 30 '18 at 22:28

0 Answers0