使用單個事件處理程序處理多個控件的事件,檢索并使用這些事件中的索引,如下例所示: ' visual basic 偽代碼 private sub mycontrol_click(sender as object, e as eventargs) messagebox.show("您已單擊 mycontrol 編號" & _ mycontrol.index) end sub
在運行時動態添加或刪除控件,如下所示: ' visual basic 偽代碼 dim i as integer for i = 1 to 5 ' 插入代碼以創建控件并為屬性分配值。 next i
在類聲明中,指定此類是從 .net 框架的 system.collections.collectionbase 類繼承而來的。 ' visual basic public class buttonarray inherits system.collections.collectionbase end class
system.collections.collectionbase 類提供集合所需的許多功能。其中包括 list 對象(跟蹤集合所包含的對象)、count 屬性(維護當前集合中的對象總數)和 removeat 方法(按特定索引刪除對象)。在實現控件數組集合時,要用到這些功能。
在組件中添加以下代碼。 ' visual basic default public readonly property item(byval index as integer) as _ system.windows.forms.button get return ctype(me.list.item(index), system.windows.forms.button) end get end property
實現 remove 方法 您已經創建了公開數組中的按鈕所需的屬性,現在可以實現從數組中刪除按鈕的機制。要從數組中刪除按鈕,必須從集合的內部 list 對象和窗體的 controls 集合中將其刪除。
實現 remove 方法
在組件中添加以下方法。 ' visual basic public sub remove() ' 檢查以確保存在要刪除的按鈕。 if me.count > 0 then ' 從宿主窗體控件集合中刪除添加到數組 ' 的最后一個按鈕。請注意在訪問數組時 ' 默認屬性的使用。 hostform.controls.remove(me(me.count -1)) me.list.removeat(me.count -1) end if end sub
在組件中添加以下方法。 ' visual basic public sub clickhandler(byval sender as object, byval e as _ system.eventargs) messagebox.show("您已單擊按鈕 " & ctype(ctype(sender, _ button).tag, string)) end sub
此方法顯示一個消息框,通過檢索存儲在按鈕的 tag 屬性中的索引來指示單擊了什么按鈕。注意,此方法的簽名與它將要處理的事件的簽名相同,這是事件處理程序所要求的。