Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It is possible to copy all the properties of a certain control? (C# window forms)

Tags:

c#

winforms

For example, I have a DataGridView control with a Blue BackgroundColor property etc.., is there a way which I can transfer or pass programatically these properties to another DataGridView control?

Something like this:

dtGrid2.Property = dtGrid1.Property; // but of course, this code is not working

Thanks...

like image 682
yonan2236 Avatar asked Aug 13 '10 03:08

yonan2236


1 Answers

You'll need to use reflection.

You grab a reference to each property in your source control (based on its type), then "get" its value - assigning that value to your target control.

Here's a crude example:

    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);
            }
        }
    }
like image 128
Stuart Helwig Avatar answered Sep 20 '22 02:09

Stuart Helwig