My vb.net program loads with ClassA. During program run, i call a Class B that makes some processes. during ClassB processing , it call a subroutine into ClassA (Main program form class), but when i do this , i found that the whole initialization of the class A occurs again, ie, the DECLARATION of class variables starts again, and the NEW subroutine occurs again.
- NB : This only occurs if I run Class B from a backgroundworker. If
ClassB was called from Form1 Main Thread, this error does not appear.
here is the code :
Public Class Form1
Dim g As String = "adsfadsf"
Public Sub New()
InitializeComponent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim clsB As New ClassB
clsB.st()
End Sub
Public Sub UpdateView()
' do update here
End Sub
End Class
Public Class ClassB
Public Sub st()
Form1.UpdateView()
End Sub
End Class
Any feedback ?
It seems that background worker is the issue since it loses reference to the parent thread. A workaround it's to pass A reference to the main thread, then use this reference to call the specific subroutine
I tried out and worked perfectly
Any code? (Can't add a comment yet :/).
You might be declaring a new instance of ClassA every time you make a reference in ClassB routine.
What you can do, if ClassA is some sort of module which stores common functions is just use its as a Shared class and Shared methods, if it is the real problem.
Related
First of all, this is my very first question in this community. Please give me some advice if I did it in the wrong way.
I need a little bit help. I am actually working on a BMEcat class library, BMEcat is a data exchange format for electronic catalogs. Anything works fine, but I realized that there is a memory problem while processing very large files. Because of this, I want to send an event for any processed article/product instead of creating a huge structure in memory.
This is the point where my problem begins.
I have a class CTRANSACTION, from which the classes CT_NEW_CATALOG, CT_UPDATE_PRODUCTS and CT_UPDATE_PRICES are derived.
In the base class CTRANSACTION there is an event defined:
Public Event Transaction_OnNewArticle(ByVal sender As Object, ByVal e As ArticleEventArgs)
The class CBMECAT has the variable
Public WithEvents TRANSACTION As CTRANSACTION
and the event handler
Private Sub TRANSACTION_Transaction_OnNewArticle(sender As Object, e As ArticleEventArgs) Handles TRANSACTION.Transaction_OnNewArticle
'...
End Sub
Because I cannot send the event Transaction_OnNewArticle from the derived CT_NEW_CATALOG class I let it call the TransactionEventOnNewArticle method instead, which is defined in CTRANSACTION. TransactionEventOnNewArticle then calls RaiseEvent Transaction_OnNewArticle.
Everything works wonderful, but the event Transaction_OnNewArticle is not fired. Is there a way to fix it?
Public MustInherit Class CTRANSACTION
Inherits CBMECAT_NODE
Public Event Transaction_OnNewArticle(ByVal sender As Object, ByVal e As ArticleEventArgs)
Public Sub TransactionEventOnNewArticle(ByVal sender As Object, ByVal e As ArticleEventArgs)
RaiseEvent Transaction_OnNewArticle(sender, e)
End Sub
Public Class CT_NEW_CATALOG
Inherits CTRANSACTION
Public Overrides Sub EventOnNewArticle(ByVal sender As Object, ByVal e As ArticleEventArgs)
TransactionEventOnNewArticle(sender, e)
End Sub
Public Class CBMECAT
Inherits CBMECAT_NODE
Public WithEvents TRANSACTION As CTRANSACTION
Private Sub TRANSACTION_Transaction_OnNewArticle(sender As Object, e As ArticleEventArgs) Handles TRANSACTION.Transaction_OnNewArticle
'THIS method is never called - why?
End Sub
End Class
UPDATE
Public Class CBMECAT_ELEMENT
Public Overridable Sub EventOnNewArticle(ByVal sender As Object, ByVal e As ArticleEventArgs)
End Sub
'Please notice that CBMECAT_ELEMENT is the base class of EVERY other class in the library.
'There is a class CBMECAT_NODE, which represents every node of the BMEcat XML structure and is derived from CBMECAT_ELEMENT.
'In CBMECAT_NODE is EventOnNewArticle called whenever an article is processed;
Public Class CBMECAT_NODE
Inherits CBMECAT_ELEMENT
Public Overridable Function CreateChildNode(ByRef Nodename As String, Optional ByRef Parent As CBMECAT_NODE = Nothing) As CBMECAT_ELEMENT
Select Case Nodename
[..]
Case ELEMENT_ARTICLE
CreateChildNode = New CARTICLE(Parent)
Dim e As New ArticleEventArgs With
{
.ARTICLE = CreateChildNode
}
EventOnNewArticle(Me, e)
[..]
UPDATE
Public Class CARTICLE
Inherits CBMECAT_NODE
Public Sub New(ByRef Father As CBMECAT_NODE)
[..]
Public Overrides Sub Read()
[..]
Public Overrides Sub Write()
[..]
Public Overrides Sub Validate()
[..]
UPDATE
Calling sequence:
CBMECAT_NODE.CreateChildNode calls CT_NEW_CATALOG.EventOnNewArticle <- OK
CT_NEW_CATALOG.EventOnNewArticle calls CTRANSACTION.TransactionEventOnNewArticle <- OK
CTRANSACTION.TransactionEventOnNewArticle fires Event Transaction_OnNewArticle
but this event is not received by the event handlier in CBMECAT
If I fire the event manually from a method in CTRANSACTION the event IS received by the event handler.
I also experimentet with AddHandler/RemoveHandler, but this also did not work.
Thank you, Visual Vincent, for helping me to focus the problem and to solve it. In deed it was "a little bit" complicated.
Class CBMECAT had the following read method:
Public Overrides Sub Read()
MyBase.Read()
GetContent(HEADER, ELEMENT_HEADER)
Select Case TransactionType
Case TransactionTypes.T_NEW_CATALOG
GetContent(TRANSACTION, ELEMENT_T_NEW_CATALOG)
Case TransactionTypes.T_UPDATE_PRICES
GetContent(TRANSACTION, ELEMENT_T_UPDATE_PRICES)
Case TransactionTypes.T_UPDATE_PRODUCTS
GetContent(TRANSACTION, ELEMENT_T_UPDATE_PRODUCTS)
Case Else
ReportError(ERROR_BMECAT_UNKNOWN_TRANSACTION_TYPE)
End Select
Validate()
End Sub
MyBase.Read reads the complete XML file and while reading it, the events should be fired. But at this moment the variable TRANSACTION is not assigned by it´s value. This is done by calling GetContent after the reading process has finished.
I have changed to:
TRANSACTION = New CT_NEW_CATALOG
TRANSACTION.Read()
Now all events are fired as expected.
I will remove TransactionEventOnNewArticle() from CBMECAT_ELEMENT. Thanks again, Vincent, for your suggestion. :-)
I'm new to VB.Net (I'm from a foxpro background) and have had my head in a book for the last two weeks trying to get started with some of the basics.
I'm trying to master class inheritance and have what I hope is not too much of a challenging question.
I've created a class and compiled it as a DLL. It simply allows me to place a button on a form. I just want to capture the Click event - which I've managed to do but would like to override the inherited code rather than having both fire which seems to be happening at the moment.
I realise I could just double click the control and enter code directly into the MyButton1 click event but wanted to trap this programmatically instead via the handler.
I thought this would just be a case of using the overridable / overrides options.
Here's the code in my class:
Imports System.Windows.Forms
Imports System.Drawing
Public Class MyButton
Inherits Windows.Forms.Button
Sub New()
End Sub
Protected Overridable Sub MyButton_Click(sender As Object, e As System.EventArgs) Handles Me.Click
MsgBox("Base Click")
End Sub
End Class
Then I place the button on my form and name it MyButton1 and in the load event:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler MyButton1.Click, AddressOf Button_Click
End Sub
Private Sub Button_Click()
MsgBox("Actual Click")
End Sub
Problem is, both events fire and I want the option to override / turn off the base event.
I thought I could just add the 'overrides' keyword to the Button_Click routine i.e.:
Private Sub Overrides Button_Click()
but I get an error message Sub Button_Click() cannot be declared 'overrides' because it does not override a sub in a base class
So to clarify - at the moment my code fires both events so I get two messages. I want to be able to turn off / supress the base class event.
Any help would be much appreciated.
I thought this would just be a case of using the overridable /
overrides options.
The fundamental problem here is that you're trying to push a square peg into a round hole.
To override something, you need to have inheritance involved. The derived class is overriding something that was inherited from the base class. For instance, if you inherited from your MyButton class to create a new type of Button called MyButtonDerived, then you could do it as expected:
Public Class MyButton
Inherits Windows.Forms.Button
Protected Overridable Sub MyButton_Click(sender As Object, e As System.EventArgs) Handles Me.Click
MsgBox("Base Click")
End Sub
End Class
Public Class MyButtonDerived
Inherits MyButton
Protected Overrides Sub MyButton_Click(sender As Object, e As EventArgs)
' We don't call the base method...
' MyBase.MyButton_Click(sender, e)
' ... and instead do something else:
MsgBox("Derived Click")
End Sub
End Class
In contrast, when you've placed MyButton onto the Form as in your original problem description, no inheritance has taken place. Instead what you've setup is "object composition"; the form contains an instance of the button (not derived from it). While it may be possible to change what happens when the button is clicked from the form itself, this is not a case that can be solved with OOP, inheritance and overriding.
If MyButton was not designed in such a way that allows the end user to suppress its base functionality, then your options are limited in how you can use it. Here is an example of what it might look like if MyButton was designed to allow the end user to suppress its base click functionality:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyButton1.SuppressDefaultClick = True
End Sub
Private Sub MyButton1_Click(sender As Object, e As EventArgs) Handles MyButton1.Click
MsgBox("Form Click Code")
End Sub
End Class
Public Class MyButton
Inherits Windows.Forms.Button
Private _suppress As Boolean = False
Public Property SuppressDefaultClick As Boolean
Get
Return _suppress
End Get
Set(value As Boolean)
_suppress = value
End Set
End Property
Protected Overridable Sub MyButton_Click(sender As Object, e As System.EventArgs) Handles Me.Click
If Not SuppressDefaultClick Then
MsgBox("Base Click")
End If
End Sub
End Class
If MyButton didn't include a way to suppress its built-in click handler like above then you'd have to resort to other means to solve your problem. In that case you'd have to prevent the button from ever receiving the message that the left mouse button has been clicked at all, and instead implement your own routine. This approach would be a considered a hack, since you are working around the limitations of something and not using it in the way it was originally intended. Here's one way the hack could be implemented:
Public Class Form1
Private WithEvents TMBC As TrapMyButtonClick
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TMBC = New TrapMyButtonClick(Me.MyButton1)
End Sub
Private Sub TMBC_Click(sender As MyButton) Handles TMBC.Click
MsgBox("Form Click Code")
End Sub
Private Class TrapMyButtonClick
Inherits NativeWindow
Private _mb As MyButton
Private Const WM_LBUTTONDOWN As Integer = &H201
Public Event Click(ByVal sender As MyButton)
Public Sub New(ByVal mb As MyButton)
If Not IsNothing(mb) AndAlso mb.IsHandleCreated Then
_mb = mb
Me.AssignHandle(mb.Handle)
End If
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case WM_LBUTTONDOWN
RaiseEvent Click(Me._mb) ' raise our custom even that the form has subscribed to
Exit Sub ' Suppress default behavior
End Select
MyBase.WndProc(m)
End Sub
End Class
End Class
Public Class MyButton
Inherits Windows.Forms.Button
Protected Overridable Sub MyButton_Click(sender As Object, e As System.EventArgs) Handles Me.Click
MsgBox("Base Click")
End Sub
End Class
You are getting 2 messages because you have set 2 different event handlers for the Click event:
The MyButton_Click method defined in your MyButton class.
The Button_Click method set in your AddHandler call on the form.
As noted in a comment above, you need to override the Button.OnClick method in your MyButton class instead of creating a new method:
Imports System.Windows.Forms
Imports System.Drawing
Public Class MyButton
Inherits Windows.Forms.Button
Sub New()
End Sub
' Override the OnClick event defined in "Button" class.
Protected Overrides Sub OnClick(e As System.EventArgs)
' Call the Click event from "Button" class.
MyBase.OnClick(e)
' Some custom events.
MsgBox("MyButton Click")
End Sub
End Class
It might be a good exercise to set breakpoints in the Button_Click and MyButton.OnClick methods so you can see exactly how the stack is created.
Consider the following code, in a brand new WinForms .NET 4.0 application, with default settings:
Public Class Form1
Private Sub AAA()
Form1.AAA(Nothing) 'cannot refer to itself through its default instance; use 'Me' instead.
End Sub
Private Shared Sub AAA(str As String)
End Sub
End Class
I am getting this error:
{FORM_CLASS_NAME} cannot refer to itself through its default instance; use 'Me' instead.
I also get this warning at the same line:
Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Assuming default instance is meant here, it ends up in an infinite loop - VS suggests to change Me.AAA() to Form1.AAA(), and then back. AAA() works in both.
Converting Private Sub AAA() to Shared solves the error. It seems like from Microsoft's point of view, all overloads must be shared, if at least one is. Or you get this default instance confusion. Why?
To clarify, I do not want to use default instance here, just do a shared call.
If anyone encountered the same situation, please advise.
Creating a variable alias that has the same name as the type of the Form class is without a doubt the single most disastrous VB.NET problem. But it was necessary to give VB6 developers a fighting chance to move to VB.NET.
The workaround is to stop trying to be explicit about what method you want to call. This compiles fine and is unambiguous, at least in your snippet:
Private Sub AAA()
AAA(Nothing) '' fine
End Sub
If that really, really hurts then simply swapping the two methods removes the ambiguity:
Private Shared Sub AAA(str As String)
End Sub
Private Sub AAA()
Form1.AAA(Nothing) '' fine
End Sub
Can you get away with this? Your usage will be very similar Form1.AAA() vs. code.AAA().
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
code.AAA()
End Sub
Private Class code
Public Shared Sub AAA()
End Sub
End Class
End Class
EDIT
Given the new information in the OP - another solution to your issue may be to use optional parameters -- ie :
Private Shared Sub AAA(Optional ByVal str As String = Nothing)
Also - the resolution works out in the "right" way if you simply change the ordering of the declarations -- this avoids the compiler error:
Private Shared Sub AAA(ByVal str As String)
End Sub
Private Sub AAA()
Form1.AAA(Nothing)
End Sub
--
Keeping this below because it can be helpful in other circumstances
Perhaps your larger application did something like this - VB is full of messes like this you can get yourself into. This will compile but it will crash :
Public Class Form1
Private Shared Sub AAA()
Form1.Text = "this"
End Sub
Private Sub Label1_TextChanged(sender As System.Object, _
e As System.EventArgs) _
Handles Label1.TextChanged
Form1.AAA()
End Sub
End Class
Just the same, this actually is "fine" (I use the term loosely)...
Public Class Form1
Private Shared dont As Boolean = True
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
dont = False
End Sub
Private Shared Sub AAA()
If Not dont Then Form1.Text = "this"
End Sub
Private Sub Label1_TextChanged(sender As System.Object, _
e As System.EventArgs) _
Handles Label1.TextChanged
Form1.AAA()
End Sub
End Class
This is because the text changed handler will fire before Form1 completes loading (ie : during InitializeComponent()!) and will refer to the default instance which is not yet finished being created - so VB tries to create a new one for you so that you can call the shared method which spins you down the infinite loop.
Oddly, the Load handler is "fine" (again, loosely) to call Form1.AAA() in - as in your opening code - because the default instance (Form1 the instance of Form1 the Class) is finished creation at that point and another won't be created to satisfy the call. Any other code path, however, that starts in the shared call and ultimately ends up touching any instance data, no matter how torturous the path, will loop around and crash.
See also : Why is there a default instance of every form in VB.Net but not in C#?
Unclear what you are trying to accomplish overall. In the OP Form1.AAA should be just AAA.
Private Sub AAA()
AAA(Nothing)
End Sub
Private Sub AAA(str As String)
If str IsNot Nothing Then MsgBox(str) ' else ???
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
AAA()
AAA("hello")
End Sub
Hey all i am trying to call a public sub within a class that resides within my form1 code:
Public Class Form1
Public Shared objItem As ListViewItem
Class Server
Private Shared Sub StringMessageReceived(ByVal sender As Object, ByVal e As StringMessageEventArgs)
MsgBox("Received message: " & Convert.ToString(e.Message))
'Form1.ListView1.Items.Add(Convert.ToString(e.Message))
Call Form1.writeToLV(Convert.ToString(e.Message))
End Sub
End Class
Public Sub writeToLV(ByRef theStuff As String)
MsgBox(theStuff)
objItem = ListView1.Items.Add(theStuff)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListView1.View = View.Details
ListView1.Columns.Add("Response", CInt(500))
End Sub
End Class
It sends the value over just fine but when it gets to putting it into the listview it never does?
Any pointers?
David
The most likely explanation is that the form that has been opened on the screen is not the default instance referenced by Form1 in the Server class.
I think that you need to restructure your code somewhat: if you are only going to have one instance of Form1, explicitly create the form and keep a reference to it in a global variable (i.e. g_Form1) rather than relying on the VB-provided default instance (assuming you are ever only going to have 1 instance of the form.
If you can have more than 1 instance of Form1, I would convert your internal Server static class to an Interface and when a new form is created, have it register itself with whatever mechanism is calling Server.StringMessageReceived.
Public Class B
End Class
Public Class D
Inherits B
End Class
Public Class SomeClass
Public Shared Sub SomeFunction2(Of TGeneric As B)()
'Is there a way that I can tell whether the the Type used
'as TGeneric is of type "B" or "D" without having
'an instance of a class also passed in?
'Reflection? How?
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SomeClass.SomeFunction2(Of D)()
End Sub
End Class
That depends on what you mean by "is of type B or D".
If you only want to differentiate between someone actually calling SomeFunction2(Of B) and SomeFunction2(Of AnyTypeThatInheritsFromB), then you can just do:
If GetType(B) Is GetType(TGeneric) Then
... they passed in B
Else
... they passed in a subclass
End If
But this seems like a bit of a code smell. Generics are intended for you not to care what the actual type is. What's the reason you need to know?