In my VB 6.0 code, I declare have the following line:
Attribute VB_Name = "MyFile"
However, in VB.NET, I get the error "expecting declaration". Isn't this a declaration statement? Is there a good reference for finding the differences between VB.NET and VB 6.0?
There's no need for the above code at all in VB.NET.
In VB 6, it specifies the name of the file from within code—this is used for things like the window title, as well as allowing you to explicitly qualify references to the members of that class in your code.
In VB.NET, the name used in the declaration of the class already serves that purpose. You no longer need to provide an explicit name with an Attribute. Consider the following mini-class:
Public Class MyFile
Public Sub DoWork()
'do something here
End Sub
End Class
To call the DoWork method of the class you've named MyFile from another place in your code, you would simply write:
MyFile.DoWork()
just as you could after you specified the VB_Name attribute under previous versions of VB.
Also note that the file name that your class/module is saved as can be something completely different; the name you specify in the class declaration is not dependent on the name you've given the file itself, just like previous versions.
Related
I have a VB.net program that I got from someone else. It is comprised of a main form and 6 other modules (all .vb files). These files all have a "VB" icon next to them in the Explorer pane. I am trying to make a call to a sub-routine in one of the modules from the main form. My line of code is:
QuoteMgr.StartGettingQuotesLevel2(sSym)
where QuoteMgr is the name of the module and StartGettingQuotesLevel2(sSym) is the name of the sub-routine. When I enter this, I get the error message:
Reference to a non-shared member requires an object reference.
The sub-routine is defined in the QuoteMgr Module as follows:
Public Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
What is strange is when I enter:
QuoteMgr.
(the name of the module with a period), it does not show me all the sub-routines and functions in the module. It only shows:
Update_Level1
Update_Level12
Update_Level2
These are Public Const in the module.
Can you tell me what I need to do?
What the compiler is trying to tell you with this error message
Reference to a non-shared member requires an object reference
is that the StartGettingQuotesLevel2 subroutine is an instance method not a shared or class method, see a more detailed explanation here
To call an instance method, you need to have an object instance to call it on. In your case, an object instance of the class type QuoteMgr. Like in the example below:
' create a new QuoteMgr object instance
Dim myQuoteMgr As QuoteMgr = New QuoteMgr()
' call its instance method with "abc" as its oSymbol argument.
myQuoteMgr.StartGettingQuotesLevel2("abc")
It is possible that you only want a single QuoteMgr object instance to be created and used by your main form. In that case, you can make it a member variable of your main form and create it once.
Public Partial Class MainForm
' Create it as a private member variable of the main form
Private m_QuoteMgr As QuoteMgr = New QuoteMgr()
' Use it when "some" button is pressed
Private Sub btnSome_Click(sender As Object, e As EventArgs) Handles btnSome.Click
m_QuoteMgr.StartGettingQuotesLevel2(txtSymbol.Text)
' And possibly do something with the results.
End Sub
End Class
Also, if instances of your QuoteMgr class depend on other object instances for their tasks, you will have to supply these to the constructor method of the QuoteMgr class as the arguments for its constructor's method parameters. Constructors (Sub New(...)) look like this:
Public Class QuoteMgr
' This is a constructor that takes two arguments
' - oMainSymbol: a string value
' - oKernel: an instance of the type Kernel
Public Sub New(oMainSymbol As String, ByRef oKernel As Kernel)
' ....
End Sub
End Class
That means, that when you create a QuoteMgr instance, you have to call its constructor method with the things it need, for example
' There must be an instance of Kernel created somewhere.
Dim myKernel As Kernel = ....
' create a new QuoteMgr object instance with these arguments:
' - oMainSymbol = "SYMABC"
' - oKernel = myKernel
Dim myQuoteMgr As QuoteMgr = New QuoteMgr("SYMABC", myKernel)
Some other recommendations
The explanations I have provided, are about basic VB.NET language features (e.g. the terms highlighted in bold). I suggest that before you make any changes to the code you have, you (1) make a backup of it, and (2) try to read a tutorial and practice on something smaller.
The compiler is (virtually) always right. When it gives you an error message, read it carefully, it will indicate the line where something is wrong and a message that tells you what it needs or is missing.
It is not the purpose of Stack Overflow to provide tutorials or code. It is a Q&A site where the best questions and answers deal with specific, delineated programming problems, for which succinct answers are possible.
Right click your application and go to Properties.
Make sure your application type is "Windows Forms Application".
It means that the routine you are trying to call needs to reference an instance of the form to access the routine. You can either reference an instance as Alex says, or you can make the routine 'Shared', so it doesn't need an instance. To do this, change the definition in QuoteMgr.vb to
Friend Shared Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
Switching it to `Shared' may start showing compiler errors, if the routine accesses form controls or module-level variables. These will need to be added to the parameter list.
According to the Microsoft documentation, to determine the number of characters in str, use the Len function. If used in a Windows Form, or any other class that has a Right property, you must fully qualify the function with "Microsoft.VisualBasic.Strings.Right".
If I set "Imports Microsoft.VisualBasic" at the top of the form I still have to use the fully qualified name in my code. Why does MS require this?
Because, without the fully qualified name, if there are two methods with the same name, the compiler cannot choose one over the other. So you should take care of the problem giving the correct hint
To ease your typing you could add at the top of your code file this version of the Imports statement
Imports VB6 = Microsoft.VisualBasic
and then you could type
Dim stringLen = VB6.Len(yourStringVariable)
This is the MSDN introduction to Namespaces in VB.NET, in particular, in the first lines of the article is explained your problem Avoiding Namespaces Collisions
NET Framework namespaces address a problem sometimes called namespace
pollution, in which the developer of a class library is hampered by
the use of similar names in another library. These conflicts with
existing components are sometimes called name collisions.
For example, if you create a new class named ListBox, you can use it
inside your project without qualification. However, if you want to use
the .NET Framework ListBox class in the same project, you must use a
fully qualified reference to make the reference unique. If the
reference is not unique, Visual Basic produces an error stating that
the name is ambiguous.
And by the way, start to use the equivalent framework methods for Right, Left, and Len.
They are still available only to help the porting of old VB6 application, (and sometime they work differently). In new applications I suggest to use
string.Substring(start, len)
string.Length
A winform, Form (derived from Control), have properties named Right and Left.
Public Class Form1
Inherits Form
Public Sub Test()
Dim location_left As Integer = Me.Left
Dim location_right As Integer = Me.Right
'Or simply:
location_left = Left '<- (Referring to Me.Left, not Microsoft.VisualBasic.Strings.Left)
location_right = Right '<- (Referring to Me.Right, not Microsoft.VisualBasic.Strings.Right)
End Sub
End Class
Therefore you'll need the use the full qualify name.
I've been using classes for a while now, but I feel I may have been using them incorrectly.
When I create the properties for the class, I just use public variables so I end up with something like the following:
Class clsMyClass
Public Name As String
End Class
However, I've been reading some info on the net and they suggest that it should be set up in the following way:
Class clsMyClass
Private Name As String
Property UsersName() As String
Get
Return Name
End Get
Set(ByVal Value As String)
Name = Value
End Set
End Property
End Class
Is the way I'm doing it extremely incorrect? If so, why? I feel like the second method adds some sort of security but to be honest, it just looks like unnecessary code..?
One advantage of properties is that they let you customise the access to your private fields and enable you to do more so you can do the following (examples, it's not limited to that):
Make a property read-only for public access
Raise an even when a property is updated
Update other private fields when a property is updated
Validate the value that is being set
See below advantages of Properties over Variables from the C# in Depth article:
• There's more fine-grained access control with properties. Need it to be publicly gettable but really only want it set with protected access? No problem (from C# 2 onwards, at least).
• Want to break into the debugger whenever the value changes? Just add a breakpoint in the setter.
• Want to log all access? Just add logging to the getter.
• Properties are used for data binding; fields aren't.
Few other points:
1) You can also make properties read-only so no one from outside the class set the values but can fetch it.
2) You can do certain actions in the get and set. i.e. Append a prefix anytime set is called
3) You can also use auto-implemented property to minimize code like below:
Public Property Name As String
You are not doing anything wrong. Properties give you a shorthand basically, a syntactic sugar.
You can still use a backing private variable and do logic in get and set if you have to while using properties. Even better is the private/protected set or get, which is again another syntactic sugar so that you won't have to write all the code manually.
First of all, VB.NET allows you to use this syntax (called shorthand property declaration - I believe since VS 2010):
Public Property Name As String
Not so much different from this (called field declaration):
Public Name As String
Second, Microsoft data binding does not work well with fields. Try this example (see below).
Example. Put a listbox called ListBox1 (default name) and a button called Button1 on an empty form in an empty WinForms project. Replace your form code with this:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lst As New List(Of clsMyClass)
lst.Add(New clsMyClass)
ListBox1.ValueMember = "Name"
ListBox1.DisplayMember = "Name"
ListBox1.DataSource = lst
End Sub
End Class
Class clsMyClass
Public Property Name As String = "Hello"
End Class
Start the application and notice that a listbox is populated with one entry, Hello. This proves that binding worked correctly. Now replace your property declaration with a field declaration instead. Start your application one more time and notice that a listbox is showing your class type converted to String. It means that your field binding did not work, and default binding was used instead, where DisplayMember is assigned sort of classInstance.ToString().
If you are curious to learn more about what happens behind the scenes, you can put a breakpoint on .DataSource assignment, and see how DisplayMember gets reset or keeps its value depending on whether you are using fields or properties.
I'm trying to get as close to function pointers / abstract classes as I can in VBA.
I have a class called VerificationManager and verifies a bunch of cells in a couple of spreadsheets match up. This will be done in different ways depending on the information and spreadsheets being used with it.
I'd like to be able to make the code reusable by specifying a method to be called in a string using the Application.Run function. So I can rewrite the function that changes.
Now if I was using Java or C# I would be able to extend an abstract class and rewrite the internals to the function. If I was using JavaScript I could store a function in a variable and pass the variable to the class and call it from there.
Inside my class I have a public property called "verificationModule" which I set to the name of the function I want it to call.
Sub VerifyWorkLocations(empLoc As EmployerLocation)
...
For i = 0 To empLoc.numOfEmp
Application.Run verificationModule, empLoc.taxdescmatch, empLoc.employees(i)
Next i
...
End Sub
However, when I try to call Application.Run I receive the following error:
Compile Error:
"Only user-defined types defined in public object modules can be
coerced to or from a variant or passed to late-bound functions"
I already tried placing my User Defined Types in a Class Module but it basically said that a class module was the wrong place for a type.
The error comes from full-fledged VB, where you can create an ActiveX dll project, create a public class there and put a UDT into that class.
In VBA, you use classes instead of UDTs when you need to coerce to or from a variant.
So just declare a class with all the fields you have in your UDT, and delete the UDT.
Alternatively, create a DLL in VB6 that would only contain the declaration of the type, and reference that dll from VBA. Or, if you're comfortable with IDL, just create a TLB file directly.
To add a module to a VBA application, try the following steps (assuming you've already entered the VBA IDE):
From the Project Explorer, right-click on your project.
Click on "Insert..."
Select "Module."
If no modules exist, a new folder within the VBA/Excel project will be created, named "Modules," and a module with a default name of "Module1" will be created.
Double-click the module to open it in the source editor.
This is where you have to place UDT's. I believe this is because of the difference in the way such types are stored internally by VBA relative to the COM-style structure of elements/objects declared/manipulated as Classes...
I am trying to call a public subroutine from a Windows form based on a string variable containing the name of the subroutine. The subroutine is a procedure in a code module and works fine when called by using the procedure name directly.
The VB.net function CallByName should work, but I don't know how to specify the module name as the "Object Ref" parameter.
In the code shown, "ReportLibrary" is a module containing the public sub with the name contained in the string strReportProcedure. This results in the following error helper:
The Help says this about the ObjectRef parameter:
ObjectRef
Type: System.Object
Required. Object. A pointer to the object exposing the property or method.
What am I missing or is it just not possible to call a routine from a module using CallByName?
CallByName will not work for code in VB.Net modules since the first parameter requires an object. You need to move the methods into a class, then create an instance of the class in order to make CallByName work.
Hmmm, I think the problem is somewhere else.
I think you haven't declared a variable like this:
Dim RL as NEW Reportlibrary
And after declaring it, use this:
CallByName(RL, strReportProcedure , CallType.Method , blnPreview)
Probably the problem was in declaration, because (in your case) your class doesn't let you access to your library's subroutines. That's why you need to declare "as New ReportLibrary".
Good Luck !
Dim object As NEW Reportlibrary and then just use that Object.