SaleNs991
SaleNs991

Reputation: 11

How to inherit a form class to another form and is it even possible?

Lately I'm having trouble with Inheriting Form1 class to other forms I create.I'm trying to create a game where user answers multiple questions,so the box (Button or PictureBox) should look like this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Question("What is the name of actor Leonardo?","Dicaprio",Button1)

End Sub

And every time I try to Inherit Form1 To Form2 (which is for example famous actors section of a game),I get error "Base class 'Form" specified for class 'Form2' cannot be different from the base class 'Form1' of one of its other partial types." When I try to modify System.Windows.Forms.Form to Form1 Or WindowsApp12.Form1 in Form2.Designer.vb,Form2 gives me an error "To prevent possible data loss before loading the designer, the following errors must be resolved:" Is there any solution? Btw. I'm working in VB.NET 2017.

Upvotes: 0

Views: 1899

Answers (2)

Mary
Mary

Reputation: 15081

When you click Add Form on the Project menu you get a form that is inheriting from System.Windows.Forms.Form. You can see this by right clicking on Form2.Designer.vb and selecting View Code. In .net OOP a class cannot inherit from more than one base class.

To get another Form1 add a class to your project.

Public Class Class1
    Inherits Form1

End Class

Then in Form1

Private Sub OPCode()
    Dim frm As New Class1
    frm.Show()
End Sub

Upvotes: 0

jmcilhinney
jmcilhinney

Reputation: 54417

When you add a form to a project, two code files are created. For a class named Form2, you would get 'Form2.vb', which is where you put all your code, and 'Form2.Designer.vb', which is where all the designer-generated code goes. You get a partial class declaration in each and the Inherits Form line is placed in the designer code file, NOT the user code file. If you then go and add Inherits Form1 in the user code file, you are now telling Form2 that it inherits both Form and Form1, which is obviously not reasonable.

The proper way to inherit from a existing form rather than the standard Form class is to select the Inherited Form item template rather than Windows Form. When you do that, you'll be prompted to select an existing form to inherit.

If you have already added the form the normal way and you want to change its base class then you need to do so in the designer code file, where it's already specified. To access the designer code file, click the 'Show All Files' button in the Solution Explorer and then expand the node for your form. You can then double-click the designer code file to open it and edit the Inherits line by hand.

Upvotes: 4

Related Questions