When adding a data to an array I keep getting the error 'System.IndexOutOfRangeException' the Array is declared to bound of 200 and at the data I'm trying to add is at 6 + 1, 6 is the variable count, in the code.
Public Class FormEvents
Dim ArrayEvents(200) As String
Dim Count As Integer
Private Sub FormEvents_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Events As String = "C:\Users\Andrew prince\Desktop\Education\College\Computing\Controlled assesment\Program\Program files\Events.txt"
Dim ObjReader As New StreamReader(Events)
ArrayEvents = ObjReader.ReadLine().Split(",")
UpdateInfo()
ObjReader.Close()
TxtEventNo.Enabled = False
BtnAdd.Enabled = False
End Sub
Sub UpdateInfo()
TxtEventNo.Text = ArrayEvents(Count)
TxtEventType.Text = ArrayEvents(Count + 1)
TxtEventDistance.Text = ArrayEvents(Count + 2)
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles BtnNext.Click
Count = Count + 3
checkInfo()
End Sub
Private Sub BtnPrev_Click(sender As Object, e As EventArgs) Handles BtnPrev.Click
Count = Count - 3
checkInfo()
End Sub
Sub Createvent()
Dim eventNo As String
eventNo = Count / 3
TxtEventNo.Text = eventNo
TxtEventDistance.Text = ""
TxtEventType.Text = ""
BtnNext.Enabled = False
BtnPrev.Enabled = False
BtnAdd.Enabled = True
End Sub
Sub checkInfo()
If Count <= 0 Then Count = 0
If ArrayEvents(Count) = "" Then Createvent() Else UpdateInfo()
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
If TxtEventDistance.Text.Length > 0 And TxtEventType.Text.Length > 0 Then AddToArray()
End Sub
Sub AddToArray()
ArrayEvents(Count) = TxtEventNo.Text
ArrayEvents(Count + 1) = TxtEventType.Text 'error occurs here in the code
ArrayEvents(Count + 2) = TxtEventDistance.Text
Enable()
End Sub
Sub Enable()
BtnAdd.Enabled = False
BtnNext.Enabled = True
BtnPrev.Enabled = True
End Sub
End Class
ArrayEvents is probably no longer 200 in length after you set it in the load method to:
ArrayEvents = ObjReader.ReadLine().Split(",")
Related
I am having trouble with the following code; it is not sending to the database
I have included all code in case there is a problem elsewhere that is effecting the sending of data to the database
The code is not throwing any errors when running or when btnBook is clicked
Imports System.Data.OleDb
Public Class frmBookRoom
Private DB As New DBControl
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Function NotEmpty(text As String) As Boolean
Return Not String.IsNullOrEmpty(text)
End Function
Private Sub AddBooking()
'Add parameters
DB.AddParam("#RoomType", cbxRoomType.Text)
DB.AddParam("#CheckIn", txtCheckIn.Text)
DB.AddParam("#Checkout", txtCheckOut.Text)
DB.AddParam("#NoNights", txtNights.Text)
DB.AddParam("#Adults", txtAdults.Text)
DB.AddParam("#Children", txtChildren.Text)
DB.AddParam("#FullName", txtName.Text)
DB.AddParam("#Revenue", txtPrice.Text)
DB.AddParam("#DateBooked", Date.Today)
'Execute insert command
DB.ExecQuery("INSERT INTO tblRoomBookings([RoomType], [CheckIn], [Checkout], [NoNights], [Adults], [Children], [FullName], [Revenue], [DateBooked])" &
"VALUES(#RoomType, #CheckIn, #Checkout, #NoNiights, #Adults, #Children, #FullName, #Revenue, #DateBooked)")
'Report and abort on errors
If Not String.IsNullOrEmpty(DB.Exception) Then MsgBox(DB.Exception) : Exit Sub
DBCon.Close()
End Sub
Private Sub btnBook_Click(sender As Object, e As EventArgs) Handles btnBook.Click
'Perform the sub routine AddBooking
AddBooking()
'Clear all the text boxes ready for the next entry
cbxRoomType.Text = Nothing
txtCheckIn.Clear()
txtCheckOut.Clear()
txtNights.Clear()
txtAdults.Text = "2"
txtChildren.Text = "0"
txtName.Clear()
txtPrice.Clear()
End Sub
Private Sub frmBookRoom_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Open connection to the database
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub frmBookRoom_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'Calendar only displays dates from today forward
MonthCalendar1.MinDate = Date.Today
End Sub
Private Sub btnLessAdults_Click(sender As Object, e As EventArgs) Handles btnLessAdults.Click
'Take one away from the number of adults
txtAdults.Text -= 1
'Don't allow the number to be less than one
If txtAdults.Text <= 1 Then txtAdults.Text = 1
End Sub
Private Sub btnMoreAdults_Click(sender As Object, e As EventArgs) Handles btnMoreAdults.Click
'Add one to the number of adults
txtAdults.Text += 1
End Sub
Private Sub btnLessChildren_Click(sender As Object, e As EventArgs) Handles btnLessChildren.Click
'Take one away from the number of children
txtChildren.Text -= 1
'Don't allow the number of children to be less than zero
If txtChildren.Text <= 0 Then txtChildren.Text = 0
End Sub
Private Sub btnMoreChildren_Click(sender As Object, e As EventArgs) Handles btnMoreChildren.Click
'Add one to the number of children
txtChildren.Text += 1
End Sub
Private Sub btnPrice_Click(sender As Object, e As EventArgs) Handles btnPrice.Click
Dim Nights As Integer
Nights = txtNights.Text
'Calculation to work out the total price of the stay
If cbxRoomType.Text = "single" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£99.99"
Else
txtPrice.Text = "£" & Format(99.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "twin" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£124.99"
Else
txtPrice.Text = "£" & Format(124.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "double" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£149.99"
Else
txtPrice.Text = "£" & Format(149.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "double double" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£164.99"
Else
txtPrice.Text = "£" & Format(164.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "mini suite" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£250"
Else
txtPrice.Text = "£" & Format(250 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "master suite" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£275"
Else
txtPrice.Text = "£" & Format(275 * (1.2 ^ Nights), "0.00")
End If
End If
btnBook.Enabled = True
End Sub
Private Sub MonthCalendar1_DateSelected(sender As Object, e As DateRangeEventArgs) Handles MonthCalendar1.DateSelected
'Automatically have the first and last date put into the corresponding textboxes
txtCheckIn.Text = MonthCalendar1.SelectionRange.Start.Date.ToString("dd/MM/yyyy")
txtCheckOut.Text = MonthCalendar1.SelectionRange.End.Date.ToString("dd/MM/yyyy")
End Sub
Private Sub cbxRoomType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxRoomType.SelectedIndexChanged, txtCheckIn.TextChanged, txtCheckOut.TextChanged, txtNights.TextChanged, txtName.TextChanged
'Enable buttons for booking and seeingg the price when the length of stay is entered
If Not String.IsNullOrWhiteSpace(txtName.Text) Then
btnPrice.Enabled = True
End If
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
'Clear the form
cbxRoomType.Text = Nothing
txtCheckIn.Clear()
txtCheckOut.Clear()
txtNights.Clear()
txtAdults.Text = "2"
txtChildren.Text = "0"
txtName.Clear()
txtPrice.Clear()
End Sub
Private Sub txtName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtName.KeyPress
'Only allow entry of letters
If Char.IsNumber(e.KeyChar) = True Then
e.Handled = True
ElseIf Char.IsPunctuation(e.KeyChar) = True Then
e.Handled = True
End If
End Sub
Private Sub btnViewEditBookings_Click(sender As Object, e As EventArgs) Handles btnViewEditBookings.Click
'Display View and Edit Bookings form
frmViewEditBookings.Show()
End Sub
Private Sub txtNights_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNights.KeyPress
'Only allow entry of numbers
If Char.IsLetter(e.KeyChar) = True Then
e.Handled = True
ElseIf Char.IsPunctuation(e.KeyChar) = True Then
e.Handled = True
End If
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
'Close the form
Me.Close()
End Sub
End Class
Thank you for your time :)
I'm super stuck on this one guys and need some help.
I have a multiple arrays Name, age, height, weight which is created on another form where all their data is entered into the arrays but then I need to go to another form where there is text box that I enter one of the name into and click search and then in a text box or list box it will show age, height, weight corresponding to the index of that name search.
My main problem is trying to get the arrays data over to another form and the other problem is trying to get the computer to search through the array know what index it is and show the corresponding data to that index for the other arrays. Been stuck on this for very long now could some please give me suggestions on how to do this it would be heavily appreciated, Thank you.
This is the code/ arrays I have so far
Imports System.IO
Public Class DataEntry
Dim Surname(200)
Dim Firstname(200)
Dim Age(200) As String
Dim HeightA(200) As String
Dim Weight(200)
Dim index As Integer
Public filepath As String = "c:\Patients\All Patients File"
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
Dim di As DirectoryInfo = New DirectoryInfo("c:\Patients")
If di.Exists Then
MsgBox("File is Already There")
txtSur.Enabled = True
txtWeight.Enabled = True
txtHeight.Enabled = True
txtFirst.Enabled = True
txtAge.Enabled = True
btnAddPatient.Enabled = True
btnClear.Enabled = True
btnFileShow.Enabled = True
btnEdit.Enabled = True
btnSave.Enabled = True
txtReader.Enabled = True
Else
di.Create()
MsgBox("File is Already There")
txtSur.Enabled = True
txtWeight.Enabled = True
txtHeight.Enabled = True
txtFirst.Enabled = True
txtAge.Enabled = True
btnAddPatient.Enabled = True
btnClear.Enabled = True
btnFileShow.Enabled = True
btnEdit.Enabled = True
btnSave.Enabled = True
txtReader.Enabled = True
End If
End Sub
Private Sub btnAddPatient_Click(sender As Object, e As EventArgs) Handles btnAddPatient.Click
index = index + 1
lblNum.Text = index
Surname(index) = txtSur.Text
Firstname(index) = txtFirst.Text
Age(index) = txtAge.Text
Weight(index) = txtWeight.Text
HeightA(index) = txtHeight.Text
Dim textAppend As String
textAppend = txtSur.Text & ", " + txtFirst.Text & ", " + txtAge.Text & ", " + txtHeight.Text & "mm" & ", " + txtWeight.Text & "kg" & "."
Try
File.AppendAllText(filepath, textAppend)
MsgBox("Patient Added Successfully")
Catch ex As Exception
MsgBox("Error Adding Patient")
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnFileShow.Click
Dim objreader As New System.IO.StreamReader("c:\Patients\All Patients File")
txtReader.Text = objreader.ReadToEnd
objreader.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
Dim result As Integer = MessageBox.Show("Are You Sure You Want To Clear", "ALERT", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
MessageBox.Show("Not Clearing")
ElseIf result = DialogResult.Yes Then
MessageBox.Show("Clearing")
End If
Dim objwriter As New System.IO.StreamWriter("c:\Patients\All Patients File")
'adding text from textbox to text fil
objwriter.Write("")
objwriter.Close()
Array.Clear(Surname, 0, Surname.Length)
Array.Clear(Firstname, 0, Firstname.Length)
Array.Clear(Age, 0, Age.Length)
Array.Clear(Weight, 0, Weight.Length)
Array.Clear(HeightA, 0, HeightA.Length)
index = 0
txtAge.Text = ""
txtFirst.Text = ""
txtHeight.Text = ""
txtSur.Text = ""
txtWeight.Text = ""
txtReader.Text = ""
End Sub
Private Sub DataEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtSur.Enabled = False
txtWeight.Enabled = False
txtHeight.Enabled = False
txtFirst.Enabled = False
txtAge.Enabled = False
btnAddPatient.Enabled = False
btnClear.Enabled = False
btnFileShow.Enabled = False
btnEdit.Enabled = False
btnSave.Enabled = False
txtReader.Enabled = False
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If txtReader.Text = "" Then
MsgBox("No Infomation To Edit")
Else
txtReader.Focus()
End If
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If txtReader.Text = "" Then
MsgBox("Nothing To Save")
Else
Dim objwriter As New System.IO.StreamWriter("c:\Patients\All Patients File")
'adding text from textbox to text file
objwriter.Write(txtReader.Text)
objwriter.Close()
MsgBox("Saved Edit")
End If
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Form1.Show()
Me.Hide()
End Sub
End Class
And this is the form I have to get the arrays over to for the search
Public Class SearchPatient
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
End Sub
In the code below I am attempting to change the tag of an existing control that was created in the array 'pictureboxes(9, 9)'. When I try to do this, I get the error 'Object reference not set to an instance of an object.'. This is done in the checkdata sub, near the bottom of the code with the comment 'Object reference not set to an instance of an object.'.
The string that is passed through to the sub is a long string of numbers, and the pictureboxes are placed into a layoutpanel if that is helpful.
I understand what this error means, I am aware that pictureboxes(i, j) is = nothing when breakpointed; I just don't know how to fix it :s
Any help is greatly appreciated and hopefully I will be quick to answer any comments/answers.
Thank you
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Net
Public Class Form1
'0 as default tile, 1 as clicked, 3 as set mine (host perspective)
Dim tiles() As Integer = {0}
Public pictureboxes(9, 9) As PictureBox
Dim flagged() As Integer
Dim clicked As Integer()
Dim columns As Integer = 10
Dim rows As Integer = 10
Dim placedMinesCount As Integer = 0
Dim formattedTag As String()
Public turn As Boolean = False
Dim stringToSend As String
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Byte = 0 To 9
For j As Byte = 0 To 9
pictureboxes(i, j) = New PictureBox
pictureboxes(i, j).Height = 60
pictureboxes(i, j).Width = 60
pictureboxes(i, j).ImageLocation = "0.png"
pictureboxes(i, j).Tag = "0|" & i & ", " & j
AddHandler pictureboxes(i, j).Click, AddressOf Tile_Click
Dim column As Integer = j
Dim row As Integer = i
Panel.Controls.Add(pictureboxes(i, j), column, row)
Next
Next
If Login.isHost = True Then
Me.Text = "Set your mines (10)"
turn = True
ElseIf Login.isHost = False Then
Me.Text = "Await your turn"
btnEndTurn.Visible = False
btnEndTurn.Enabled = False
End If
End Sub
Protected Sub Tile_Click(ByVal sender As Object, ByVal e As EventArgs)
formatSenderTag(sender.tag)
If Login.isHost = True Then
Dim clickAction As String = formattedTag(0)
Select Case clickAction
Case "0"
If placedMinesCount < 10 Then
placedMinesCount = placedMinesCount + 1
sender.imagelocation = "3.png"
sender.tag = "3"
Me.Text = "Set your mines (" & 10 - placedMinesCount & ")"
ElseIf placedMinesCount >= 10 Then
MsgBox("You have placed all of your 10 Mines")
End If
Case "2"
MsgBox("You cannot set a mine here")
Case "3"
placedMinesCount = placedMinesCount - 1
Me.Text = "Set your mines (" & 10 - placedMinesCount & ")"
sender.imagelocation = "0.png"
sender.tag = "0"
End Select
ElseIf Login.isHost = False Then
Dim clickAction As String = formattedTag(0)
Select Case clickAction
Case "0"
sender.tag = "1"
sender.imagelocation = "1.png"
Case "3"
MsgBox("Game Over")
Case "2"
MsgBox("Already Clicked")
End Select
End If
End Sub
Private Sub formatSenderTag(ByVal sender As String)
'split into array
'element 0 as TILE TYPE
'element 1 as TILE LOCATION
formattedTag = sender.Split(New String() {"|"}, StringSplitOptions.None)
End Sub
Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
End
End Sub
Private Sub btnEndTurn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEndTurn.Click
turn = False
gridtostring()
senddata()
End Sub
Private Sub gridtostring()
For i As Byte = 0 To 9
For j As Byte = 0 To 9
formatSenderTag(pictureboxes(i, j).Tag & "|")
stringToSend = stringToSend & formattedTag(0)
Next
Next
End Sub
Private Sub senddata()
'***SEND STUFF
'Assuming you have a textbox with the data you want to send
If (Not String.IsNullOrEmpty(stringToSend)) Then
Dim data() As Byte = Encoding.ASCII.GetBytes(stringToSend)
Login.sendingClient.Send(data, data.Length)
End If
End Sub
Public Sub checkdata(ByVal data As String)
If Not data = stringToSend Then
'Dim loopcount As Integer = 0
For i As Byte = 0 To 9
For j As Byte = 0 To 9
Dim loopcount As Integer = (i.ToString & j.ToString) + 1
'Dim pineapple As String = pictureboxes(i, j).Tag
'pictureboxes(i, j).Tag = GetChar(data, 3)
pictureboxes(i, j).Tag = GetChar(data, loopcount) & "|" & i & ", " & j '***Object reference not set to an instance of an object.***
formatSenderTag(pictureboxes(i, j).Tag)
pictureboxes(i, j).ImageLocation = formattedTag(0)
pictureboxes(i, j).ImageLocation = "0.png"
'Panel.Controls(pictureboxes(i, j).Tag) = GetChar(data, 3) '.Tag = GetChar(data, 3)
Next
Next
End If
End Sub
End Class
***AND BELOW IS THE OTHER FORM WHICH CALLS CHECKDATA()
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Net
Public Class Login
Dim Port As Integer = 8123
Private Const broadcastAddress As String = "255.255.255.255"
Public receivingClient As UdpClient
Public sendingClient As UdpClient
Dim sendAddress As String
Dim ServerMode As Boolean = False
Public isHost As Boolean = true
Dim returndata As String
Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub ComboWANLAN_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboWANLAN.SelectedIndexChanged
If ComboWANLAN.Text = "Online (WAN)" Then
txtSendAddress.Enabled = True
ElseIf ComboWANLAN.Text = "Offline (LAN)" Then
txtSendAddress.Enabled = False
End If
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
'***START PORT LISTENING/SENDING AND NETWORKING STUFFS
Port = txtPort.Text
InitializeSender()
InitializeReceiver()
End Sub
Private Sub btnHost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHost.Click
'***START PORT LISTENING/SENDING AND NETWORKING STUFFS
Port = txtPort.Text
InitializeSender()
InitializeReceiver()
isHost = True
Me.Hide()
Form1.Show()
End Sub
Private Sub InitializeSender()
If ComboWANLAN.Text = "Offline (LAN)" Then
sendingClient = New UdpClient(broadcastAddress, Port)
'Use broadcastAddress for sending data locally (on LAN), otherwise you'll need the public (or global) IP address of the machine that you want to send your data to
ElseIf ComboWANLAN.Text = "Online (WAN)" Then
sendAddress = txtSendAddress.Text
sendingClient = New UdpClient(sendAddress, Port)
'Use broadcastAddress for sending data locally (on LAN), otherwise you'll need the public (or global) IP address of the machine that you want to send your data to
End If
sendingClient.EnableBroadcast = True
End Sub
Private Sub InitializeReceiver()
receivingClient = New UdpClient(Port)
ThreadPool.QueueUserWorkItem(AddressOf Receiver) 'Start listener on another thread
End Sub
Private Sub Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port) 'Listen for incoming data from any IP on the specified port
Do While True 'Notice that i've setup an infinite loop to continually listen for incoming data
Dim data() As Byte
data = receivingClient.Receive(endPoint)
If Form1.turn = False Then
returndata = Encoding.ASCII.GetString(data) 'Recived data as string
Form1.checkdata(returndata)
End If
Loop
End Sub
Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
End
End Sub
End Class
***STACK TRACE
at Minesweeper.Form1.checkdata(String data) in c:\users\harry\documents\visual studio 2010\Projects\Minesweeper\Minesweeper\Form1.vb:line 139
at Minesweeper.Login.Receiver() in C:\Users\Harry\Documents\Visual Studio 2010\Projects\Minesweeper\Minesweeper\Login.vb:line 71
at Minesweeper.Login._Lambda$__1(Object a0) in C:\Users\Harry\Documents\Visual Studio 2010\Projects\Minesweeper\Minesweeper\Login.vb:line 61
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Note: Screwed up with the spacings in some places
This code does not give an error with the data you gave:
checkdata("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
Public Sub checkdata(ByVal data As String)
If Not data = stringToSend Then
'Dim loopcount As Integer = 0
For i As Byte = 0 To 9
For j As Byte = 0 To 9
Dim loopcount As Integer = (i.ToString & j.ToString) + 1
'Dim pineapple As String = pictureboxes(i, j).Tag
'pictureboxes(i, j).Tag = GetChar(data, 3)
pictureboxes(i, j).Tag = GetChar(data, loopcount) & "|" & i & ", " & j '***Object reference not set to an instance of an object.***
formatSenderTag(pictureboxes(i, j).Tag)
pictureboxes(i, j).ImageLocation = formattedTag(0)
pictureboxes(i, j).ImageLocation = "0.png"
'Panel.Controls(pictureboxes(i, j).Tag) = GetChar(data, 3) '.Tag = GetChar(data, 3)
Next
Next
End If
End Sub
Looking at your stack trace and code, you are missing the instantiation of Form1 in your login class. I think this can be the problem.
Try adding this to the beginning of your Login class:
Dim Form1 as New Form1
I'm building a program that using a service based database.
My first problem:
I want that when somebody clicks on one of the colors it will store a String in the database like "color_red"
Second problem:
I want that each radio button will store a different integer
Database Schema:
Relevant code:
Public Class Form2
Private Sub TableBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TableBindingNavigatorSaveItem.Click
Me.Validate()
Me.TableBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Database1)
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1.Table' table. You can move, or remove it, as needed.
Me.TableTableAdapter.Fill(Me.Database1.Table)
End Sub
Private Sub TableDataGridView_CellContentClick(sender As Object, e As DataGridViewCellEventArgs)
End Sub
Private Sub TableBindingNavigator_RefreshItems(sender As Object, e As EventArgs) Handles TableBindingNavigator.RefreshItems
End Sub
Private Sub Nb_typeRadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles Nb_typeRadioButton.CheckedChanged
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
PictureBox1.BorderStyle = BorderStyle.Fixed3D
PictureBox2.BorderStyle = BorderStyle.FixedSingle
PictureBox3.BorderStyle = BorderStyle.FixedSingle
PictureBox4.BorderStyle = BorderStyle.FixedSingle
PictureBox5.BorderStyle = BorderStyle.FixedSingle
End Sub
Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles PictureBox2.Click
PictureBox1.BorderStyle = BorderStyle.FixedSingle
PictureBox2.BorderStyle = BorderStyle.Fixed3D
PictureBox3.BorderStyle = BorderStyle.FixedSingle
PictureBox4.BorderStyle = BorderStyle.FixedSingle
PictureBox5.BorderStyle = BorderStyle.FixedSingle
End Sub
Private Sub PictureBox3_Click(sender As Object, e As EventArgs) Handles PictureBox3.Click
PictureBox1.BorderStyle = BorderStyle.FixedSingle
PictureBox2.BorderStyle = BorderStyle.FixedSingle
PictureBox3.BorderStyle = BorderStyle.Fixed3D
PictureBox4.BorderStyle = BorderStyle.FixedSingle
PictureBox5.BorderStyle = BorderStyle.FixedSingle
End Sub
Private Sub PictureBox4_Click(sender As Object, e As EventArgs) Handles PictureBox4.Click
PictureBox1.BorderStyle = BorderStyle.FixedSingle
PictureBox2.BorderStyle = BorderStyle.FixedSingle
PictureBox3.BorderStyle = BorderStyle.FixedSingle
PictureBox4.BorderStyle = BorderStyle.Fixed3D
PictureBox5.BorderStyle = BorderStyle.FixedSingle
End Sub
Private Sub PictureBox5_Click(sender As Object, e As EventArgs) Handles PictureBox5.Click
PictureBox1.BorderStyle = BorderStyle.FixedSingle
PictureBox2.BorderStyle = BorderStyle.FixedSingle
PictureBox3.BorderStyle = BorderStyle.FixedSingle
PictureBox4.BorderStyle = BorderStyle.FixedSingle
PictureBox5.BorderStyle = BorderStyle.Fixed3D
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Me.Validate()
Me.TableBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Database1)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try
Dim db As New Database1TableAdapters.TableTableAdapter
Dim dbimg As String = db.GetData.Rows(0).Item(1)
PictureBox1.Image = My.Resources.ResourceManager.GetObject(dbimg)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
I will update my answer as soon as you provide more quality information.
For now here is what I understood you want to do:
In Button.Click event you should write:
If Me.Radiobutton1.Checked = True than
Value = 1 '' For Example
Else
Value = 2 '' For Example
End If
Or you can do it like this:
If Me.Radiobutton1.Checked = True than
Value = 1
ElseIf Me.Radiobutton2.Checked = True than
Value = 2
End if
This is about giving values according to checked RadioButton.
And about marked PictureBox I would just add to Button.Click event:
If Me.PictureBox1.BorderStyle = BorderStyle.Fixed3D Then
StringValue = 1
ElseIf Me.PictureBox2.BorderStyle = BorderStyle.Fixed3D Then
StringValue = 2
ElseIf Me.PictureBox3.BorderStyle = BorderStyle.Fixed3D Then
StringValue = 3
ElseIf Me.PictureBox4.BorderStyle = BorderStyle.Fixed3D Then
StringValue = 4
ElseIf Me.PictureBox5.BorderStyle = BorderStyle.Fixed3D Then
StringValue = 5
End If
I'm working on a project for college in which I have to create a program which stored twenty questions and answers entered on a teachers form which are then displayed one after the other (after clicking the next button) on a student form.
the issue I'm having is that I can enter the questions and answers ( array 0 to 19) however when the students are answering the questions only 19 are shown with the last question not appearing.
Let me know what I can show you to help solve my issue.
Module Module1
Public myQ(0 To 19) As String
Public myA(0 To 19) As String
End Module
Public Class frmTeacher
Public myCounter As Integer
Private Sub frmTeacher_Load(sender As Object, e As EventArgs) Handles MyBase.Load
myCounter = (0)
End Sub
Private Sub btnTeacherNext_Click(sender As Object, e As EventArgs) Handles btnTeacherNext.Click
If myCounter < 19 Then
myQ(myCounter) = txtTeacherQ.Text
myA(myCounter) = txtTeacherA.Text
myCounter = myCounter + 1
txtTeacherQ.Text = ""
txtTeacherA.Text = ""
Else
MsgBox("20 Questions Created, Moving on To Student Screen")
Me.Hide()
frmStudent1.Show()
End If
End Sub
Public Class frmStudent1
Dim myScore As Integer
Dim MyCounter2 As Integer
Public myNames As String
Private Sub btnStudentHelp_Click(sender As Object, e As EventArgs) Handles btnStudentHelp.Click
MsgBox("Questions will be shown to the left, Place your answer into the box on the right and click next")
End Sub
Private Sub frmStudent1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblStudentQ.Text = myQ(0)
HideItAll()
txtStudentName.Visible = True
btnStart.Visible = True
End Sub
Private Sub HideItAll()
lblStudentQ.Visible = False
txtStudentA.Visible = False
txtStudentName.Visible = False
btnStudentHelp.Visible = False
btnNextStudent.Visible = False
btnStart.Visible = False
btnStudentNext.Visible = False
End Sub
Private Sub btnStudentNext_Click(sender As Object, e As EventArgs) Handles btnStudentNext.Click
If MyCounter2 < 19 Then
If txtStudentA.Text = myA(MyCounter2) Then
myScore = myScore + 1
End If
MyCounter2 = MyCounter2 + 1
lblStudentQ.Text = myQ(MyCounter2)
Else
MsgBox("Your score is " + Str(myScore))
myNames = myNames + txtStudentName.Text + ": " + Str(myScore) + vbNewLine
HideItAll()
btnNextStudent.Visible = True
End If
End Sub
Private Sub btnNextStudent_Click(sender As Object, e As EventArgs) Handles btnNextStudent.Click
Me.Refresh()
HideItAll()
txtStudentName.Visible = True
btnStart.Visible = True
End Sub
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
myScore = 0
MyCounter2 = 0
If txtStudentName.Text = "teacher" Then
MsgBox("The scores are as follows: " + vbNewLine + myNames)
End If
HideItAll()
lblStudentQ.Visible = True
txtStudentA.Visible = True
btnStudentHelp.Visible = True
btnStudentNext.Visible = True
End Sub
End Class
change this:
If MyCounter2 < 19 Then
to:
If MyCounter2 < 20 Then
or:
If MyCounter2 <= 19 Then
When you declare your arrays as
Public myQ(0 To 19) As String
you have effectively created an array that could hosts 20 strings and their indexes are from 0 to 19 max. This means that your myCounter2 variable could have as maximum value 19 otherwise you go out of bound of the array. At the same time if you show only the questions and answers that have an index less that 19 you loose the last couple of question/answer
You should fix your code using this kind of conditional
If MyCounter2 < myQ.Length Then
.....
Array.Length returns the number of elements that could be stored in all the dimensions of the array (20).
Using this property is better because, if you change the array size (say you want to ask 40 questions getting 40 answers) then you don't need to check every line of your code to adjust magic numbers appearing everywhere.
But, after the change, this line of the btnStudentNext_Clicks event fails when MyCounter2 value is 19
' MyCounter2 = 19 + 1
MyCounter2 = MyCounter2 + 1
' this fails because at this point MyCounter2 is 20
lblStudentQ.Text = myQ(MyCounter2)
A possible refactoring of your code could be
Private Sub btnStudentNext_Click(sender As Object, e As EventArgs) Handles btnStudentNext.Click
If MyCounter2 < myQ.Length Then
If txtStudentA.Text = myA(MyCounter2) Then
myScore = myScore + 1
End If
MyCounter2 = MyCounter2 + 1
End if
if MyCounter2 >= myQ.Length Then
ShowResults();
else
lblStudentQ.Text = myQ(MyCounter2)
txtStudentA.Text = ""
Endif
End Sub
Private Sub ShowResults()
MsgBox("Your score is " + Str(myScore))
myNames = myNames + txtStudentName.Text + ": " + Str(myScore) + vbNewLine
HideItAll()
btnNextStudent.Visible = True
End Sub