tags:

views:

40

answers:

2

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...

A: 

You could use reflection to get all the public properties of the type and copy the values from one instance to another, but this is dangerous and might not really duplicate the entire state of the object. There might be some properties that you don't want to copy (e.g. Parent, Site), and other important properties that you can't set directly (e.g. Columns, Rows). Also, there could be properties that are reference types; your copied control would end up referencing the same object as your original, which could be undesirable. There could also be state information that can only be set through method calls, which won't be copied this way. In short, reflection probably isn't the solution you're looking for.

You may just have to manually copy the properties you want. Alternatively, you could create a factory method that can create any number of similar grids.

CodeSavvyGeek
... However, you need to be careful because if you do it blindly, you would end up copying properties like `Parent`, `Name` and `Location` which you might not want.
Timwi
@Timwi: I modified my answer to point out the dangers of using reflection this way.
CodeSavvyGeek
A: 

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);
            }
        }
    }
Stuart Helwig
Note the comment under CodeSawyGeek's answer - this code blindly copies every property. Could be dangerous.
Stuart Helwig
Hm, you check for a set method but not for a get method (although I admit write-only properties are rare). But note that your code would copy properties like `Parent`, `Name` and `Location` which may not be desired.
Timwi
thanks to you guys....
yonan2236
Using reflection this way is probably not going to give you the results you want. A DataGridView is a very complex object, and you might not be able to completely (or correctly) copy it by blindly copying its property values.
CodeSavvyGeek