08robertsj
08robertsj

Reputation: 344

How to set the class of a vb.NET control after it's been created already

I have a Windows Form with 7 Picture Boxes on it that are called PropButton1 through to PropButton7. I know they aren't buttons but I'm using them as buttons anyway (normal buttons aren't suitable for this purpose).

I want to add a custom "File Path" property to the Picture Boxes. To do this I've created a separate class that inherits the PictureBox class:

Public Class PropButton
    Inherits PictureBox
    Private SoundFilePath As String

    Public Property SoundFile() As String
        Get
            Return SoundFilePath
        End Get
        Set(value As String)
            SoundFilePath = value
        End Set
    End Property

End Class

I want to convert the original Picture Boxes from PictureBox to PropButton so I can read and write to things like PropButton1.SoundFilePath and I preferably want to do this without having to delete all of my Picture Boxes and start again. Is there a way to do this?

Upvotes: 0

Views: 510

Answers (2)

Hans Passant
Hans Passant

Reputation: 941277

Yes, that is possible with the text editor. The Visual Basic IDE hides too much information, first thing you want to do is click the "Show All Files" icon in the Solution Explorer window. That adds a node next to your form in the same window, open it and double-click the Designer.vb file. Note the InitializeComponent() method and the declarations at the bottom of the file, you see the PictureBoxes being declared and initialized.

You can now simply Edit+Replace "System.Windows.Forms.PictureBox" with "PropButton".

Ensure you have a good backup before you do this.

Upvotes: 1

Jens
Jens

Reputation: 6375

In Visual Studio look to the right in the Solution Explorer. It has a toolbar button to Show all files. Click it and you will see that you can expand the tree nodes for the forms and they contain three files. One that contains your source code, and another one called a Designer. The Designer file is automatically generated by Visual Studio and in most cases it should not be touched.

When you open the designer file you see all the initializations of the controls on your form and their declarations. Here you can easily change the declarations of your pictureboxes so that they are created as PropButtons instead.

Just be careful what you change here, because it can mess up the Visual Studio designer. But it is good to know what happens behind the scenes.

Look here first:
enter image description here

Change this...
enter image description here

...to this.
enter image description here

Upvotes: 2

Related Questions