Sum won't increment in visual basics 2013 - vb.net

I'm having this codes at all forms so I could have a sum of score in my quiz. But when the score form shows up in the end, it shows 0 and is more likely not incrementing when i have a wright or wrong answer. I'm sorry its my first time to make in VB basics. Wish someone could help.
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles NextButton1.Click
If Option2.Checked Then
Score.ScoreRight.Text = Score.ScoreRight.Text + 1
Dim Form2 As New Form3
Form3.Show()
Me.Hide()
Else
Score.ScoreWrong.Text = Score.ScoreWrong.Text + 1
Dim Form2 As New Form3
Form3.Show()
Me.Hide()
End If
End Sub
End Class

I'm assuming that Score is a form and that Score.Scoreright and score.scorewrong are textboxes in that form
try this maybe
Public class Score
Dim withevents Form2instance as new Form2
Dim withevents Form3instance as new Form3
Dim rightAnsweres as integer = 0
Dim wronganswers as integer = 0
Public sub Updateresults()
Scoreright.text = rightansweres
ScoreWrong.text = wronganswers
End Sub
Public sub Form2Instance_QuestionAnswered()Handles Form2Instance.QuestionAnswered
if Form2Instance.AnsweredCorrectly = true then
rightansweres = rightansweres+1
else
wronganswers = wronganswers + 1
end if
Form2instance.Hide
UpdateResults()
Form3instance.show
end sub
end class
Now in your form2 and form3 classes you need an event and you need to raise the event when the question is answered.
Public Class Form2
Public event QuestionAnswered()
Property AnsweredCorrectly as integer = False
Sub RunThisAfterYouHaveIndicatedWhetherOrNotTheAnswerWasCorrect()
RaiseEvent QuestionAnswered()
End Sub
end class
Now to explain
You are trying to call a routine inside of a general class type and expecting the results to be updated inside of an active instance of that class. Or so it seems.
You have to have some kind of reference to the instance of the class that you're trying to update.
In this example, The class you're trying to update has a reference to the forms that it needs information from. It receives the information by waiting for the form to raise an event and then handles it's business.

Is Option2 a checkbox? If so, i think you need to use the .checkstatus property of the checkbox instead of .checked
If Option2.checkedstate = checkedstate.checked then

Related

How to access parent form properties from a child form in vb.net

I have pretty much the same problem as described in this, but using VB.NET. There is a Form1 which is opened automatically as start window, so I cannot find the instance to use for accessing it. There is a Form2 opened from within Form1. I try to pass the instance of Form1 using keyword "Me":
Private Sub Button1_click(...) Handles Button1.Click
Dim childform as new Form2(Me)
childform.show()
End Sub
In Form2 I have:
Public Sub New(parentform As System.Windows.Forms.Form)
InitializeComponents()
MessageBox.Show(parentform.Button1.Text)
End Sub
Upon compiling I get the error: "Button1 is not a member of Form".
So how to pass the Form1 instance correctly to Form2?
Also I want to change some properties of the Button1 of Form1 from Form2. Button1 is declared in a Private Sub, will I nevertheless be able to access it from Form2 if I pass the instance correctly? If not, can I declaring a sub in Form1, e.g.
Public Shared Sub ChangeText(newtext As Sting)
Me.Button1.Text=newtext
End Sub
that will do the job?
I'm not 100% sure about what you are trying to achieve, but, you can pass data between forms. So for example you can do something like:
Public Class Form1
Private Sub Button1_click(...) Handles Button1.Click
Dim newForm2 as New Form2()
newForm2.stringText = ""
If newForm2.ShowDialog() = DialogResult.OK Then
Button1.Text = newForm2.stringText
End If
End Sub
End Class
And in Form2 you have
Public Class Form2
Dim stringText as string
Private Sub changeStringText()
'your method to change your data
Me.DialogResult = DialogResult.OK 'this will close form2
End Sub
End Class
I hope this is what you need, if not let me know
Thanks for your answer and comment. So I declared the wrong class for the parentform, means in Form2 it needs to be "parentform as Form1":
Public Sub New(parentform As Form1)
InitializeComponents()
MessageBox.Show(parentform.Button1.Text)
End Sub
and yes, I need to skip the "shared" in the ChangeText:
Public Sub ChangeText(newtext As Sting)
Me.Button1.Text=newtext
End Sub
This way it worked for me.

How to pass value of a label from one form to another form in VB.NET?

I am new in Vb.net. I'm still studying the logics in this language. I want to output data in a label.text from form 1 to form 2 with the use of a button. How can I do that while both forms are running?
PS. label.text may change value every time I click the button.
Here are two options.
Use a property setter
Use a method
Note: The code below assumes the following:
Form1: Button (name: Button1)
Form2: Label (name: Label1)
When the button is clicked on Form1, if Form2 isn't open, it opens it. Additionally, the value of the label on Form2 is set.
Option 1: (use a property setter)
Form1.vb
Public Class Form1
Dim counter As Integer = 0
Dim f2 As Form2 = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If f2 Is Nothing Then
'create new instance
f2 = New Form2
'show form
f2.Show()
Else
'show window
'if window is minimized, it will "unminimize" it
'f2.WindowState = FormWindowState.Normal
'bring window into focus
'also brings the window to front
'f2.Activate()
End If
'set value
Dim username As String = String.Format("user{0}", counter)
'set property value
f2.Username = username
counter += 1
End Sub
End Class
Form2.vb
Public Class Form2
Dim _username As String = String.Empty
Public Property Username As String
Get
Return _username
End Get
Set(value As String)
_username = value
Label1.Text = value
Label1.Refresh()
End Set
End Property
End Class
Option 2: (use a method)
Form1.vb
Public Class Form1
Dim counter As Integer = 0
Dim f2 As Form2 = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If f2 Is Nothing Then
'create new instance
f2 = New Form2
'show form
f2.Show()
Else
'show window
'if window is minimized, it will "unminimize" it
'f2.WindowState = FormWindowState.Normal
'bring window into focus
'also brings the window to front
'f2.Activate()
End If
'set value
Dim username As String = String.Format("user{0}", counter)
'set value using method
f2.SetLabelText(username)
counter += 1
End Sub
End Class
Form2.vb
Public Class Form2
Public Sub SetLabelText(ByVal username As String)
Label1.Text = username
Label1.Refresh()
End Sub
End Class
Resources:
How to: Create a Property (Visual Basic)

Trying to assign pictures to PictureBoxes in VB

I am trying to create a simple game, and first it needs to randomly load 16 PictureBoxes with images. I am not sure where the problem lies in this.
Public Class Form1
Private picArrows() As PictureBox = {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
'starts a new game
'declares RNG
Dim randGen As New Random
'uses RNG to determine arrow placement
For intPicBox As Integer = 0 To 15
Select Case randGen.Next(1, 5)
Case 1
picArrows(intPicBox).Image = My.Resources.Up
Case 2
picArrows(intPicBox).Image = My.Resources.Right
Case 3
picArrows(intPicBox).Image = My.Resources.Down
Case 4
picArrows(intPicBox).Image = My.Resources.Left
End Select
Next
End Sub
End Class
I get a NullReferenceException error on the line after Case X. Anyone know what I'm doing wrong?
I get a NullReferenceException error on the line after Case X
You cannot initialize your array like this:
Public Class Form1
Private picArrows() As PictureBox = {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
The Form has not been initialized yet, so it and all the controls on it have not been created yet. As a result, all those control references are going to be Nothing, leaving you with an array full of Nothings. The result is a NullReferenceException because Nothing does not have an Image property.
You can declare the array there, but you can only initialize it after the form's constructor runs (Sub New). Form Load is a good place:
Public Class Form1
Private picArrows As PictureBox()
' for best results you should use the same RNG over and over too:
Private randGen As New Random()
...
Private Sub Form_Load(....
picArrows = New PictureBox() {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
See also NullReference Exception in Visual Basic
Slightly different arrangement without the companion array:
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
With New Random
For col = 1 To 4
For row = 1 To 4
CType(Controls(String.Format("pic{0}{1}", col, row)), PictureBox).Image = {My.Resources.Up, My.Resources.Right, My.Resources.Down, My.Resources.Left}(.Next(0, 4))
Next
Next
End With
End Sub

How to call a Sub without knowing which form is loaded into panel?

On every DataGridView1_SelectionChanged event I need to run a Private Sub OnSelectionChanged() of the form that is loaded into Panel1 (see the image http://tinypic.com/r/2nu2wx/8).
Every form that can be loaded into Panel1 has the same Private Sub OnSelectionChanged() that initiates all the necessary calculations. For instance, I can load a form that calculates temperatures or I can load a form that calculates voltages. If different element is selected in the main form’s DataGridView1, either temperatures or voltages should be recalculated.
The problem is - there are many forms that can be loaded into Panel1, and I’m struggling to raise an event that would fire only once and would run the necessary Sub only in the loaded form.
Currently I’m using Shared Event:
'Main form (Form1).
Shared Event event_UpdateLoadedForm(ByVal frm_name As String)
'This is how I load forms into a panel (in this case frm_SCT).
Private Sub mnu_SCT_Click(sender As Object, e As EventArgs) Handles mnu_SCT.Click
frm_SCT.TopLevel = False
frm_SCT.Dock = DockStyle.Fill
Panel1.Controls.Add(frm_SCT)
frm_SCT.Show()
Var._loadedForm = frm_SCT.Name
RaiseEvent event_UpdateLoadedForm(Var._loadedForm)
End Sub
‘Form that is loaded into panel (Form2 or Form3 or Form4...).
Private WithEvents myEvent As New Form1
Private Sub OnEvent(ByVal frm_name As String) Handles myEvent.event_UpdateLoadedForm
‘Avoid executing code for the form that is not loaded.
If frm_name <> Me.Name Then Exit Sub
End Sub
This approach is working but I’m sure it can be done way better (I'd be thankful for any suggestions). I have tried to raise an event in the main form like this:
Public Event MyEvent As EventHandler
Protected Overridable Sub OnChange(e As EventArgs)
RaiseEvent MyEvent(Me, e)
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) _
Handles DataGridView1.SelectionChanged
OnChange(EventArgs.Empty)
End Sub
but I don't know to subscribe to it in the loaded form.
Thank you.
Taking into account Hans Passant’s comments as well as code he posted in related thread I achieved what I wanted (see the code below).
Public Interface IOnEvent
Sub OnSelectionChange()
End Interface
Public Class Form1
' ???
Private myInterface As IOnEvent = Nothing
' Create and load form.
Private Sub DisplayForm(frm_Name As String)
' Exit if the form is already displayed.
If Panel1.Controls.Count > 0 AndAlso _
Panel1.Controls(0).GetType().Name = frm_Name Then Exit Sub
' Dispose previous form.
Do While Panel1.Controls.Count > 0
Panel1.Controls(0).Dispose()
Loop
' Create form by its full name.
Dim T As Type = Type.GetType("Namespace." & frm_Name)
Dim frm As Form = CType(Activator.CreateInstance(T), Form)
' Load form into the panel.
frm.TopLevel = False
frm.Visible = True
frm.Dock = DockStyle.Fill
Panel1.Controls.Add(frm)
' ???
myInterface = DirectCast(frm, IOnEvent)
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) _
Handles DataGridView1.SelectionChanged
' Avoid error if the panel is empty.
If myInterface Is Nothing Then Return
' Run subroutine in the loaded form.
myInterface.OnSelectionChange()
End Sub
End Class
One last thing – it would be great if someone could take a quick look at the code (it works) and confirm that it is ok, especially the lines marked with “???” (I don’t understand them yet).

Send integer value from form to another visual basic

I am making a game with score but i cant send the score from the first form to the second one
The score start with 1000
When the user play it decrease
How to send the value after it decrease to a label in form2
Without any code to see - I would guess that your issue is that forms don't have a reference of some sort to each other.
I would suggest making a module (and put it in a Namespace):
Namespace MyModule
Module Module1
Public f1 as Form1
Public f2 as Form2
Public Sub setScore() as String
' This assumes Form1 has a public variable playerScore,
' and Form2 has a label scoreLabel
f2.scoreLabel.Text = f1.playerScore
End Sub
End Module
End Namespace
Second step to this is to make sure in both of your forms, you set the references in the module to that form (example below for Form1 done in the Load event). Be sure that both f1 and f2 have been defined, otherwise you will get a null reference exception when you try to call setScore().
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyModule.f1 = Me
' ... and the rest of your code in form load
End Sub
Lastly, when your score changes, just call the setScore() sub in MyModule
playerScore += 1 'example
MyModule.setScore() ' update the label in Form2