1

i am working on a "DataGridView" in C# 3.5, in "winforms" application.

I have a custom column is "MaskTextColumn", i have some custom properties in it like : Mask, "PromptChar" etc.

When i am making clone of "MaskTextColumn" my customer properties is not copied to new object, i want to make clone as it is with custom property value.

Haider Ali Wajihi
  • 2,756
  • 7
  • 51
  • 82

2 Answers2

2

You should override the clone method to include your custom properties. As this link states,

When overriding Clone ... be sure to also copy the values of any properties that were added to the derived class.

The code goes like this:

public override Object Clone()
{
    object clonedObject = base.Clone();
    MaskTextColumn clonedColumn = clonedObject as MaskTextColumn;
    clonedColumn.PromptChar = this.PromptChar;
    // .. more property settings here
    return clonedColumn;
}
Dmitry Reznik
  • 6,812
  • 2
  • 32
  • 27
2

You need to override the Clone method in your custom derived class.

Something like this:

public override object Clone() 
{
    var clonedColumn = base.Clone() as CustomColumn;
    clonedColumn.CustomProp = this.CustomProp;
    return clonedColumn;
}
user974608
  • 242
  • 1
  • 8
  • I don't think this will work. `base.Clone()`'s return value will be a MaskTextColumn so the `as CustomColumn` will make clonedColumn variable null and next line will throw NullReferenceException. – Marcel Gosselin Mar 24 '12 at 20:32
  • this method will apply as it is in CustomCell Class where base.Clone() as will return Class's object – Haider Ali Wajihi Mar 26 '12 at 08:09