Working with Multiple Forms in Visual Basic .NET: Upgrading to .NET

xiaoxiao2021-03-06  66

Introduction

IN Microsoft® Visual Basic® 6.0, IF You Had A Second Form (Form2) in Your Project, The Displaying It Was As Easy As Form2.Show. That Code Is No Longer Correct In Visual Basic .NET Due To some Changes in How Forms are handled. For programmers moving from an earlier version of Visual Basic to .NET, these changes can make the simple task of displaying a second form seem very difficult. In this article, I will illustrate how Visual Basic .NET forms differ from previous versions And how you can work with multiple form forning the new model.

Visual Basic 6.0 vs. Visual Basic .NET

Forms, in either version of Visual Basic, are essentially the same as any other class;. They have properties, methods, and events, and you can create multiple instances of them So, assuming you have a form in your project called Form2, the Visual Basic 6.0 Code Shown Here Creates Three Instances of That Form and Displays Them All:

DIM Myfirstform as form2

DIM Mysecondform as form2

DIM Mythirdform as form2

SET myfirstform = new form2

Set mysecondform = new form2

Set mythirdform = new form2

Myfirstform.show

Mysecondform.show

Mythirdform.show

Now, other than the use of the keyword Set to assign new Form2 instances to your three variables, this code will also work in Visual Basic .NET, and both languages ​​will display three copies of Form2 if this code is run. In this example, Form2 is behaving as a class, and you have to create an instance of a class before you can use it, but a special feature of Visual Basic prior to .NET allows you to work with Forms without creating an instance. This change in behavior in Visual Basic .NET can cause a great deal of confusion. In Visual Basic 6.0 and earlier versions, a special default instance of each form is automatically created for you, and allows you to use the form's name to access this instance. What this means is That The Visual Basic 6.0 Code "form2.show" HAS The Effect of Showing The "Default" Instance of Form2, But It Doesn't Work At All In Visual Basic .Net. in .Net There is no default instance; form2 refers ONLY To The Class That Repens Your Form, And this class Cannot Be Used without creating an instance.

That is the key difference between .NET and previous versions of Visual Basic-you need an instance of a form before you can display it or work with any of its controls or properties-but the second part of the problem is that these special default form instances are global to your entire project in Visual Basic 6.0. Taking these two facts together means that (in Visual Basic 6.0 or earlier) you can refer to any form in your project from anywhere in your code and you will always be referring to the same . instance of that form with the button's Click event on one of your forms you could show Form2 with "Form2.Show," and then set the text of a text box on Form2 from code in a module just like this: Form2.TextBox1. TEXT = "fred"

If you try to do the same type of code in Visual Basic .NET, you will run into the error message Reference to a Non-Shared Member Requires an Object Reference, which means that you tried to call a method or use a property of a Class instead of an instance. A Quick Solution to this problem is to create an instance in Every Case Where You Are Receiving The Error Message, Turbire:

Form2.show ()

INTO:

DIM MyFORM2 AS New Form2 ()

MyForm2.show ()

THIS WIOWORKISESES, But if you have had code somewhere else in your project what accessed That Default Instance of form2 and you fix it

Form2.textBox1.text = "fred"

INTO:

DIM MyFORM2 AS New Form2 ()

MyForm2.TextBox1.text = "fred"

then you will have trouble, because this code has created a new instance of Form2; you are not working with the same instance you created earlier You will not get any errors (there is nothing wrong with the preceding code), but you won. 'T See Any Change On The Instance of Form2 That You Called Show () on erlier.how the Upgrade Wizard Handles this item

If you upgrade a Visual Basic 6.0 project, the Upgrade Wizard adds some special code to each of your forms to provide you with the default instance functionality that you were able to use in earlier versions of Visual Basic. This code, wrapped in a region labeled "Upgrade Support," Adds a Shared Property That Returns An Instance of The Underlying form:

Private shared m_vb6formdefinstance as form1

Private shared m_initializingdefinstance as boolean

Public Shared Property Definstance () AS Form1

Get

IF m_vb6formdefinstance is nothing_

Oralse m_vb6formdefinstance.isdisposed then

m_initializingdefinstance = true

m_vb6formdefinstance = new form1 ()

m_initializingdefinstance = false

END IF

Definstance = M_VB6FORMDEFINSTANCE

END GET

Set (ByVal Value As Form1)

m_vb6formdefinstance = value

End set

End Property

As a shared property, DefInstance is accessible using just the form's name, and the same instance of the form is returned for everyone using this class within a single application. With this code added to your form (s), you can write code that mimics The Behavior of the Visual Basic 6.0 Examples Shown Earlier by Specifying Form2.definstance Instead of Just Form2.

With this code added, you can use Form2.DefInstance.Show () and then Form2.DefInstance.TextBox1.Text = "Fred" instead of directly referencing Form2. If you are not using the Upgrade Wizard you can achieve similar results by adding the code just shown (and the code from an upgraded form's New procedure, as that is also required) to your own Visual Basic .NET forms. Alternatively, though, if you are not upgrading existing code, you will be better off if you adjust your Programming style to handle the lack of default instances for forms. The remainder of this article will focus on showing you how to do what.interacting with other forms in .net

If you are coming from earlier versions of Visual Basic it can be difficult to work without default instances of your forms. The following sections illustrate how to handle several specific scenarios and should help you with your own programming tasks.

Keeping a Reference Around

As mentioned earlier, the most important concept to understand about programming with forms is that you need an instance of a form before you can do anything with it, and if you want to use the same instance in multiple places then you will need to pass a . reference to that instance around for many Visual Basic 6.0 programmers, this is a totally new problem; the default instance provided for each form is available to all the code in your project There are two main ways to handle your form reference (s). : Either Make It To Each Form, Class, Module, or Procedure That Requires IT.

Global Data IN .NET

Earlier I mentioned that global variables are not available in Visual Basic .NET, and now I'm going to tell you how to make something global How will you ever trust me after this Actually, I am not being dishonest in either case.?; global variables are not allowed in Visual Basic .NET, but you can achieve similar functionality using Shared (called static in C #) class members. A Shared class member, as used by the Visual Basic Upgrade Wizard when it adds the DefInstance property to your forms IS Available Without Creating An Instance of a Class and, IT IS A Property, ITS Value Is Shared Across Your Entire Application. You Could Therefore Create A Class Like this: Public Class MyForms

Private Shared M_Customerform As Customerform

Public Shared Property Customerform () As Customerform

Get

Return M_Customerform

END GET

SET (Byval Value As Customerform)

m_customerform = value

End set

End Property

END CLASS

When you first create an instance of your form you could Store It Into this class:

DIM Mynewcust As New Customerform ()

mynewcust.show ()

MyForms.customerform = mynewcust

After the customerform, you cald the custom, you cald, you.

Module DoingstuffwithForms

Sub doexcitingthings ()

myForms.customerform.Text = _

Datetime.now (). TolongTimeString

End Sub

End module

Storing your form in this manner comes as close to Visual Basic 6.0's Global variables as you are going to get. The next level of variable scope below this level is class (module, class or form, actually) scope, where a variable is Declared With, and is available to any code in That Class, And Below That Is Procedure Scope, WHERE A Variable Is Local To a Single Routine.Passing Your Form Around

As an alternative to making your form global, you could instead keep a reference to the form as a variable in your form or class and then pass that reference to any code that needs access to your form. If you had a form (called Form1 in this example) and you wanted to open a second form (Form2) when a button was clicked, and then do some calculations on this new form in response to another button being clicked, your code could be written within Form1, like this:

Public Class Form1

Inherits System.Windows.Forms.form

DIM MyFORM2 AS FORM2

Private sub button1_click (byval sender as system.Object, _

Byval e as system.eventargs) Handles Button1.click

MyForm2 = new form2 ()

MyForm2.show ()

End Sub

Private sub button2_click (byval sender as system.object, _

Byval e as system.eventargs) Handles Button2.click

Calculation.comPoundInterestCalc (MyForm2)

End Sub

END CLASS

Either method-global references or passing form instances as arguments-will work, but you should pick a method best suited for your particular project. In a situation where only a few procedures will need access to your form after creating it, I would tend towards having a form parameter on those procedures and passing your form reference in as needed. If a form is being used by many procedures throughout your project, a global reference might be in order, but consider restructuring your application so that only a single class or procedure actually needs access to your form. If you were using your form as a place to write out logging information, for instance, you could create a class that exposed the form as a shared member, but also provided a shared WriteToLogWindow method that handled the actual Intertion with the form. All of Your Code Would I That WriteTologWindow Method Instead of Accessing The Form Directly: Public Class Log

Private Shared M_Logform as Form2

Public Shared Property Logform () AS Form2

Get

Return M_Logform

END GET

Set (Byval Value As Form2)

M_Logform = Value

End set

End Property

Public Shared Sub WriteTologWindow (Byval Message As String)

DIM SB AS New_

Stringbuilder (m_logform.txtLoginfo.text)

Sb.append (Environment.newline)

Sb.append (Message)

m_logform.txtLoginfo.text = sb.tostring ()

End Sub

END CLASS

Getting Information Into and Out of Forms

Thus far in this article I have covered how to obtain and keep track of a form instance, but I have not discussed how you would get information into and out of form. If you have a form instance, and if your code and your form are from the same project, you can access the controls on a form directly, but I do not think that is the best idea. Instead of working with the text boxes, buttons, and other controls on your form, I suggest creating properties that are explicitly made Public and allow you to set and retrieve the values ​​you wish to access Follow me through a quick example if you wish to try out this method of working with a form:. Create a new Windows Application project in Visual Basic .NET. One form, Form1, will be created automatically. Add another by right-clicking your project in the Solution Explorer and selecting Add Windows form. Accept the default name of Form2.vb and click OK. Add two buttons to Form1, leave them with their DEFAULT NAMES OF Button1 and button2, and reposit ion them enough so that they are not overlapping. Add a single text box to Form2, leaving it with the default name of TextBox1. Now add this code to Form2 (by right-clicking Form2 in the Solution Explorer and selecting View Code) immediately before "End Class." Public Property Customername () AS STRING

Get

Return TEXTBOX1.TEXT

END GET

Set (byval value as string)

TextBox1.text = value

End set

End Property to do this:

View the code for Form1 and add the following line after "Inherits System.Windows.Forms.Form": Dim myForm2 As New Form2 () Double-Click Button1 on Form1 to access the button's Click event handler and enter this code: myForm2.CustomerName = "Fred"

myForm2.Show () Double-Click Button2 on Form1 and enter this code: MessageBox.Show (myForm2.CustomerName) myForm2.CustomerName = "Joe" Run the project (F5), and then click Button1 and Button2 to see the code in action .

. Having a CustomerName property might not seem like a big deviation from accessing the text box on Form2 directly, but you gain a few benefits from interacting with your forms in this way The main benefit is abstraction; you do not have to know anything about the controls on Form2 (there might not even be a text box on it), just set and retrieve the CustomerName property. Having this layer of abstraction allows Form2 to change its implementation without any effect on the rest of your code, making future modifications much easier. In our example, the property-based version was not any easier to use, but if you are dealing with a more complex user interface, the code behind your properties could handle all the details while the code to use the form stayed very . simple of course, one final benefit of this model is less tangible but certainly has value to many developers: Using properties instead of directly accessing the controls is much more elegant and results in code that is easier to un Derstand.

Conclusion

Visual Basic .NET gets rid of the "default instance" used by forms in earlier versions, and that change can cause a great deal of confusion to those trying to learn how to program in .NET. You need an instance of a form before you can access its properties, methods, or any of its controls, and you need that instance stored in such a way that it is available throughout your code. The .NET system for handling forms is more consistent and more powerful than the system in Visual Basic 6.0, but even changes for the better can cause confusion for those trying to make the transition.For additional information, see the Visual Studio .NET product documentation topics: Upgrading from Visual Basic 6.0 and Forms Changes in Visual Basic .NET.

转载请注明原文地址:https://www.9cbs.com/read-111879.html

New Post(0)