Kobarin's Development Blog

C#やASP.NETなどについての記録です。

コントロールのクローンを生成

ASP.NETには、コントロールのクローンを生成するメソッドがない。
以下、ソース。Sourceと同じ型のコントロールを作り出してプロパティを全てコピーするだけだが、
IDの付与のみ状況によって書き換えが必要になるケース有り。

  /// 
  /// コントロールのコピー
  /// 
  /// コピー元のコントロール
  /// コピー先コントロールIDに振る連番
  /// 
  public Control ControlCopy(Control ctrlSource, int ctrlNumber)
  {
    Type t = ctrlSource.GetType();

    Control ctrlDest = (Control)t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, null, null);

    foreach (System.Reflection.PropertyInfo prop in t.GetProperties())
    {
      if (prop.CanWrite)
      {
        if (prop.Name == "ID")
        {
          ctrlDest.ID = ctrlSource.ID + ctrlNumber.ToString();
        }
        else
        {
          prop.SetValue(ctrlDest, prop.GetValue(ctrlSource, null), null);
        }
      }
    }

    return ctrlDest;
  }