Reputation: 101251
I want to extend the basic ControlCollection
in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables.
So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality.
But when I run the example, it gives a NullReferenceException
.
Here is the code:
Shadows Sub add(ByVal text As String)
Dim LB As New Label
LB.AutoSize = True
LB.Text = text
MyBase.Add(LB) 'Here it gives the exception.
End Sub
I searched on Google, and someone said that the CreateControlsInstance
method needs to be overriden. So I did that, but then it gives InvalidOperationException
with an innerException
message of NullReferenceException
.
How do I to implement this?
Upvotes: 0
Views: 1445
Reputation: 5871
If you're inheriting from Control.ControlCollection then you need to provide a New method in your class. Your New method must call ControlCollection's constructor (MyBase.New) and pass it a valid parent control.
If you haven't done this correctly, the NullReferenceException will be thrown in the Add method.
This could also be causing the InvalidOperationException in your CreateControlsInstance method
The following code calls the constructor incorrectly causing the Add method to throw a NullReferenceException...
Public Class MyControlCollection
Inherits Control.ControlCollection
Sub New()
'Bad - you need to pass a valid control instance
'to the constructor
MyBase.New(Nothing)
End Sub
Public Shadows Sub Add(ByVal text As String)
Dim LB As New Label()
LB.AutoSize = True
LB.Text = text
'The next line will throw a NullReferenceException
MyBase.Add(LB)
End Sub
End Class
Upvotes: 0
Reputation: 28443
Why not inherit from UserControl to define a custom control that has properties like Text and Image?
Upvotes: 3
Reputation: 15451
You are probably better off using just a generic collection anyways. Bieng Control Collection doesnt really do anything special for it.
puclic class MyCollection : Collection<Control>
Upvotes: 0