How can i access goto with other class. the first code as my first class and the bottom code was my second class. i want to execute that line of class1 using goto by the second class.Heres my code maybe someone will understand what i mean.
Class1
Next4sides: 'My label here
'MsgBox(ObjectFunction.count)
If ObjectFunction.count = 1 Then
Me.Size = New Size(506, 200)
CreateObject.AddTextBox()
CreateObject.AddLabel()
CreateObject.lbl.Text = "Square"
CreateObject.txtbox.Text = "Enter length side"
CreateObject.txtbox.Name = "txtlengthside"
cmbox.Visible = False
ElseIf ObjectFunction.count = 2 Then
CreateObject.AddTextBox()
CreateObject.AddTwoTextBox()
CreateObject.lbl.Text = "Rectangle"
CreateObject.txtbox.Text = "Enter width"
CreateObject.txtbox.Name = "txtrecwidth"
CreateObject.txtbox1.Text = "Enter height"
CreateObject.txtbox1.Name = "txtrecheight"
End If
I want to access the label "Next4sides:" from this class2
If count = 1 Then
If (String.Compare(CType(Form1.Controls("txtlengthside"), TextBox).Text, "return", True) <> 0) Then
If e.KeyChar.Equals(Microsoft.VisualBasic.ChrW(Keys.Return)) Then
Shape.setSquare(CType(Form1.Controls("txtlengthside"), TextBox).Text)
MsgBox("Type Return In The Box to Return to main menu" & vbNewLine & vbNewLine & "Answer" & vbNewLine & "Area: " & Shape.getTriangle() & vbNewLine & vbNewLine & "Next is Rectangle")
count = count + 1
CreateObject.txtbox.Dispose()
'FROM THIS LINE I WANT TO ACCESS THE LABEL USING GoTo
End If
Else
Application.Restart()
End If
Related
I have a wpf vb.net application (written in VS 2019 community) containing two website searches. The first search is a string search and that either produces one result, which I then load into the second search, or it produces more than one result, which I load into a combobox to let the user choose. My problem is getting the application to stop and allow the user to choose from the combobox. I have implemented a workaround that uses a modal form containing a combobox and this allows the user to choose from the combobox and supply the value to the second search. I have been advised to use the 'change' event for the combobox but there isn't one available, I have also been advised to use the selectedindexchanged but the control doesn't let the dropdown list occur to select anything. I have also tried using various forms of addhandler (commented out in the code below).
' Build the 'Search API' URL.
Dim uri = New Uri("https://api.themoviedb.org/3/search/tv?" _
& "api_key=" & TMDBAPIKey _
& "&language=en-US" _
& "&query=" & sLvl1NodeName _
& "&page=1" _
& "&first_air_date_year=" & sFirstXmitYear)
' Retrieve the IMDB ID with an API Search function using the series title
Try
Dim Site = New WebClient()
Answer = Site.DownloadString(uri)
Catch ex As NullReferenceException
Dim messagetext As String = "The 'Search API' from GetDetails popup failed with : " _
& ex.Message & " for: Title=" & sLvl1NodeName
Me.txtErrorMessageBox.Text = messagetext
Exit Sub
End Try
' Deserialise the answer
Dim JsonElem As TMDBtitle = JsonConvert.DeserializeObject(Of TMDBtitle)(Answer)
' If the websearch finds only one result this is the TV series we want, if more than
' one result is found load the results into a combobox and get the user to choose.
If JsonElem.results.Length = 1 Then
TVSeriesID = JsonElem.results(0).id
Else
Me.cmbChooseSeries.BeginUpdate()
Me.lblChooseSeries.Text = Me.lblChooseSeries.Text & "( " & JsonElem.results.Length & " )"
Me.cmbChooseSeries.Items.Clear()
For Each titleresult In JsonElem.results
ComboSeriesChoice = titleresult.name & " | " &
titleresult.id & " | " &
titleresult.first_air_date & " | " &
titleresult.overview
Me.cmbChooseSeries.Items.Add(ComboSeriesChoice)
Next
cmbChooseSeries.DroppedDown = True
Me.cmbChooseSeries.EndUpdate()
If cmbChooseSeries.SelectedIndex <> -1 Then
Dim var1 = cmbChooseSeries.SelectedText
Else
Threading.Thread.Sleep(3000)
End If
'AddHandler cmbChooseSeries.MouseDoubleClick,
'Sub()
'Threading.Thread.Sleep(3000)
'End Sub
TVSeriesID = cmbChooseSeries.SelectedItem
End If
' Build the 'TV Search API' call URL.
Dim urix = New Uri("https://api.themoviedb.org/3/tv/" _
& TVSeriesID & "?" _
& "api_key=" & TMDBAPIKey _
& "&language=en-US")
Try
Dim site = New WebClient()
Answer = site.DownloadString(urix) ' download the JSON from the server.
Catch ex As NullReferenceException
Dim MessageText As String = "The 'TV Search API' from GetDetails popup failed with : " _
& ex.Message & " for: Title=" & sLvl1NodeName & " ID=" & popupid
Me.txtErrorMessageBox.Text = MessageText
Exit Sub
End Try
Dim jsonelemx = JsonConvert.DeserializeObject(Of TVResult)(Answer)
lstDetailItems(0) = "Name"
lstDetailItems(1) = jsonelemx.name
lstDetailItems(2) = (String.Empty)
Dim DelItems = New ListViewItem(lstDetailItems)
Me.lstSeriesDetails.Items.Add(DelItems)
lstDetailItems(0) = "Status"
lstDetailItems(1) = jsonelemx.status
lstDetailItems(2) = (String.Empty)
DelItems = New ListViewItem(lstDetailItems)
Me.lstSeriesDetails.Items.Add(DelItems)
lstDetailItems(0) = "Episode run time"
lstDetailItems(1) = Convert.ToString(jsonelemx.episode_run_time(0))
lstDetailItems(2) = (String.Empty)
DelItems = New ListViewItem(lstDetailItems)
Me.lstSeriesDetails.Items.Add(DelItems)
So I get this error when trying to run my code "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" I am not exactly sure what the issue is. The user should be able to enter 3 assignment grades and then see the averages
I marked the line where I get the error with 'THIS IS THE ERROR'
Public Class GradeBook
Dim grade(9, 2) As Integer 'Store 10 student grades on 3 tests'
Dim studentCount As Integer = 0 'Number of students entered'
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GradeListBox.Items.Add(vbTab & vbTab & "Test 1" & vbTab & "Test 2" & vbTab & "Test 3" & vbTab & "Average")
End Sub
Private Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
grade(studentCount, 0) = Convert.ToInt32(Assignment1TextBox.Text)
grade(studentCount, 1) = Convert.ToInt32(Assignment2TextBox.Text)
grade(studentCount, 2) = Convert.ToInt32(Assignment3TextBox.Text)
Dim output As String = "Student " & studentCount & vbTab
For column = 0 To grade.GetUpperBound(1)
If LetterRadioButton.Checked = True Then
output &= vbTab & LetterGrade(grade(studentCount, column))
Else
output &= vbTab & grade(studentCount, column)
End If
Next
output &= vbTab & CalculateStudentAverage(studentCount)
GradeListBox.Items.Add(output)
studentCount += 1
AverageLabel.Text = CalculateClassAverage()
displayBarChart()
End Sub
Function LetterGrade(ByVal grade As Double) As String
Dim output As String = ""
Select Case grade
Case Is >= 90
output = "A"
Case Is >= 80
output = "B"
Case Is >= 70
output = "C"
Case Is >= 60
output = "D"
Case Is >= 50
output = "E"
End Select
Return output
End Function
Function CalculateStudentAverage(ByVal row As Integer) As String
Dim gradeTotal As Integer = 0
For column = 0 To grade.GetUpperBound(1)
gradeTotal += grade(row, column) 'THIS IS THE ERROR'
Next
Dim studentAverage As String = String.Empty
If LetterRadioButton.Checked = True Then
studentAverage = LetterGrade(gradeTotal / (grade.GetUpperBound(1) + 1))
Else
studentAverage = String.Format("{0:F}", (gradeTotal / grade.GetUpperBound(1) + 1))
End If
Return studentAverage
End Function
Function CalculateClassAverage() As String
Dim classTotal As Integer = 0
For row = 0 To studentCount - 1
For column = 0 To grade.GetUpperBound(1)
classTotal += grade(row, column)
Next
Next
Dim classAverage As String = String.Empty
If LetterRadioButton.Checked = True Then
classAverage = LetterGrade(classTotal / (studentCount * (grade.GetUpperBound(1) + 1)))
Else
classAverage = String.Format("{0:F}", (classTotal / (studentCount * (grade.GetUpperBound(1) + 1))))
End If
Return classAverage
End Function
Sub displayBarChart()
GradeListBox.Items.Clear()
GradeListBox.Items.Add(vbTab & vbTab & "Test 1" & vbTab & "Test 2" & vbTab & "Test 3" & vbTab & "Average")
For row = 0 To studentCount - 1
Dim output As String = "Student " & row & vbTab
For column = 0 To grade.GetUpperBound(1)
If LetterRadioButton.Checked = True Then
output &= vbTab & LetterGrade(grade(row, column))
Else
output &= vbTab & (grade(row, column))
End If
Next
output &= vbTab & CalculateStudentAverage(studentCount)
GradeListBox.Items.Add(output)
studentCount += 1
AverageLabel.Text = CalculateClassAverage()
displayBarChart()
Assignment1TextBox.Clear()
Assignment2TextBox.Clear()
Assignment3TextBox.Clear()
If studentCount = grade.GetUpperBound(0) + 1 Then
InputGradeGroupBox.Enabled = False
End If
Next
End Sub
End Class
To be honest, I suspect you're going about it in a way not suited to OOP. Using arrays for multiple peices of data is prone to error and harder to maintain later.
Lets have a think about how you want to represent your data. You have a bunch of students. In a more complete example each student would have a name, personal details such as address, a list of the courses they're taking and for each course, a list of assignments and scores for each assignment which can also be represented as a grade.
So in essence you have a class called Student and the various bits of information are properties of that student.
Finally you have a list of these students
In your code, you simply have a student number and three assignment scores.
Your basic student class should have the properties of Number, Test1Score, Test2Score and Test3Score. You would also want to be able to get the grade from each score, the average of all the scores and the average of all the grades.
The code below defines the Student class with that information in mind
Friend Class Student
Public Property Number As Integer
Public Property Test1Score As Integer
Public Property Test2Score As Integer
Public Property Test3Score As Integer
Public Function Test1Grade() As String
Return LetterGrade(Test1Score)
End Function
Public Function Test2Grade() As String
Return LetterGrade(Test2Score)
End Function
Public Function Test3Grade() As String
Return LetterGrade(Test3Score)
End Function
Friend Shared Function LetterGrade(ByVal grade As Double) As String
Dim output As String = ""
Select Case grade
Case Is >= 90
output = "A"
Case Is >= 80
output = "B"
Case Is >= 70
output = "C"
Case Is >= 60
output = "D"
Case Is >= 50
output = "E"
Case Else
output = "F"
End Select
Return output
End Function
Friend Function AverageScore() As Double
Return (Test1Score + Test2Score + Test3Score) / 3
End Function
Friend Function AverageGrade() As String
Dim avgscore As Double = AverageScore()
Return LetterGrade(avgscore)
End Function
End Class
The function LetterGrade is Shared so that it can be used in your main form to calculate the average grade for the entire class.
OK Next think about how you want your program to work. You'll need a list of students, so at the beginning of your form class , you'll need this..
Public Class Form1
Private Students As New List(Of Student)
This way, instead of trying to keep track of your variable studentCount you can just use the .Count property of the List e.g Students.Count. You wont need to any adding to it as the Students list keeps track of it automatically.
Next, you'll want the function that calculates the average score/grade of the class..
Function CalculateClassAverage() As String
Dim classTotal As Integer = 0
For Each tmpStudent As Student In Students
With tmpStudent
classTotal += .Test1Score + .Test2Score + .Test3Score
End With
Next
Dim classAverage As String = String.Empty
If LetterRadioButton.Checked = True Then
classAverage = Student.LetterGrade((classTotal / Students.Count) / 3)
Else
classAverage = String.Format("{0:F}", (classTotal / (Students.Count)) / 3)
End If
Return classAverage
End Function
As you can see, there are a number of differences here because of the way your data is stored, but you should be able to follow it. One difference is the With statement, this allows you to save on typing. inside the With.. End With block, instead of typing tmpstudent.Test1Score etc, you can just type .Test1Score
The other thing of note is this line ..
classAverage = Student.LetterGrade( ... etc
You may think that there has been no declaration of a variable called Student. There IS a class, but not a variable. What this is actually doing is calling the LetterGrade function that is shared in the Student class definition.. Have a look at shared functions.
Next is the code to display the information in the ListBox. I haven't changed the name even though it is misleading btw.
Sub displayBarChart()
GradeListBox.Items.Clear()
GradeListBox.Items.Add(vbTab & vbTab & "Test 1" & vbTab & "Test 2" & vbTab & "Test 3" & vbTab & "Average")
For Each tmpstudent As Student In Students
Dim output As String = "Student " & tmpstudent.Number & vbTab
With tmpstudent
If LetterRadioButton.Checked = True Then
output &= .Test1Grade & vbTab & .Test2Grade & vbTab & .Test3Grade & vbTab & .AverageGrade
Else
output &= .Test1Score & vbTab & .Test2Score & vbTab & .Test3Score & vbTab & .AverageScore
End If
End With
GradeListBox.Items.Add(output)
AverageLabel.Text = CalculateClassAverage()
Next
If Students.Count = 10 Then
InputGradeGroupBox.Enabled = False
End If
End Sub
More use of the With..End With statements again, but the rest should be straighforward to follow.
A little extra bit of code.. When you click on the LetterRadioButton, the data in the listBox and ClassAveragelabel are refreshed with the appropriate letters/grades
Private Sub LetterRadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles LetterRadioButton.CheckedChanged
AverageLabel.Text = CalculateClassAverage()
displayBarChart()
End Sub
Finally, to bring it all together, you have the code for the button click..
Private Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click
Dim tmpStudent As New Student With {.Number = Students.Count + 1,
.Test1Score = Convert.ToDouble(Assignment1TextBox.Text),
.Test2Score = Convert.ToDouble(Assignment2TextBox.Text),
.Test3Score = Convert.ToDouble(Assignment3TextBox.Text)}
Dim output As String = "Student " & tmpStudent.Number & vbTab
With tmpStudent
If LetterRadioButton.Checked = True Then
output &= vbTab & .Test1Grade & vbTab & .Test2Grade & vbTab & .Test3Grade
Else
output &= vbTab & .Test1Score & vbTab & .Test2Score & vbTab & .Test3Score
End If
End With
Students.Add(tmpStudent)
If LetterRadioButton.Checked Then
output &= vbTab & tmpStudent.AverageGrade
Else
output &= vbTab & tmpStudent.AverageScore
End If
GradeListBox.Items.Add(output)
AverageLabel.Text = CalculateClassAverage()
displayBarChart()
Assignment1TextBox.Clear()
Assignment2TextBox.Clear()
Assignment3TextBox.Clear()
End Sub
Hopefully in addition to my comment to your question, this provides a slightly better insight of OOP.
I've got a large subroutine (1958 lines) to calculate some prices and figures based on a complex decision tree.
The figures will be in one of multiple tables, so to check if there is an applicable set of data to use, I've got the following If statement
If dDt.Rows.Count = 0 And cDt.Rows.Count = 0 And p1Dt.Rows.Count = 0 And p2Dt.Rows.Count = 0 And p3Dt.Rows.Count = 0 Then
If SysAQ = False Then
Me.Cursor = Cursors.Default
MessageBox.Show("There are no rates in the system for " & cmbSupplier.Text & "/" & ugr.Cells("Product_Code").Value & "/" & cmbCustCode.Text & " for todays " & _
"date. Please add one and try again.", "No Rate Exists", MessageBoxButtons.OK, MessageBoxIcon.Information)
ugr.Cells("DSC_Code").Value = ""
ugr.Cells("DSC_Rate").Value = 0
ugr.Cells("DSC_Value").Value = 0
ugr.Cells("DSC_VAT").Value = 0
Exit Sub
ElseIf suppAQ = False Then
Me.Cursor = Cursors.Default
MessageBox.Show("There are no rates in the system for " & cmbSupplier.Text & "/" & ugr.Cells("Product_Code").Value & "/" & cmbCustCode.Text & " for todays " & _
"date. Please add one and try again.", "No Rate Exists", MessageBoxButtons.OK, MessageBoxIcon.Information)
ugr.Cells("DSC_Code").Value = ""
ugr.Cells("DSC_Rate").Value = 0
ugr.Cells("DSC_Value").Value = 0
ugr.Cells("DSC_VAT").Value = 0
Exit Sub
ElseIf aDt.Rows.Count = 0 Then
Me.Cursor = Cursors.Default
MessageBox.Show("There are no rates in the system for " & cmbSupplier.Text & "/" & ugr.Cells("Product_Code").Value & "/" & cmbCustCode.Text & " for todays " & _
"date. Please add one and try again.", "No Rate Exists", MessageBoxButtons.OK, MessageBoxIcon.Information)
ugr.Cells("DSC_Code").Value = ""
ugr.Cells("DSC_Rate").Value = 0
ugr.Cells("DSC_Value").Value = 0
ugr.Cells("DSC_VAT").Value = 0
Exit Sub
End If
End If
This block of code is within a For Loop, For Each ugr As UltraGridRow in ugLines.Rows
This means it's checking if there is a price for the product on the line, and if not, alerts the user and exits the subroutine.
This subroutine is called on ugLines.AfterRowInsert, (Once a product has been added), as well as before saving the full data.
It works fine for the latter scenario, as whenever it detects a line with no price, it will error and not save. However, if a product has been added with no price, then the user adds another product, it will never add the price in or tell the user the new line is missing a price as the first one always fails.
What I'm wondering, is if there is another way to set this out? Instead of having Exit Sub, can I change it to skip the rest of the code and jump straight to the next iteration? I've looked at using Continue and Continue For, but that seems to be only applicable if checking the opposite, to check where each product does have a price in at least one of the tables, making the If Statement more complex - Is there another way around this?
Essentially, just changing the code in your question to the following:
Dim noRatesInSystem As Boolean = False
If dDt.Rows.Count = 0 And cDt.Rows.Count = 0 And p1Dt.Rows.Count = 0 And p2Dt.Rows.Count = 0 And p3Dt.Rows.Count = 0 Then
If SysAQ = False OrElse suppAQ = False OrElse aDt.Rows.Count = 0 Then
Me.Cursor = Cursors.Default
MessageBox.Show("There are no rates in the system for " & cmbSupplier.Text & "/" & ugr.Cells("Product_Code").Value & "/" & cmbCustCode.Text & " for todays " & _
"date. Please add one and try again.", "No Rate Exists", MessageBoxButtons.OK, MessageBoxIcon.Information)
ugr.Cells("DSC_Code").Value = ""
ugr.Cells("DSC_Rate").Value = 0
ugr.Cells("DSC_Value").Value = 0
ugr.Cells("DSC_VAT").Value = 0
noRatesInSystem = True
End If
End If
If noRatesInSystem = True Then Continue For
This will A) Tidy up the If Statement, B) Continue the loop if a price is found and C) Skip the iteration (Jump to Next) if there are no prices found.
I have a radio button in my VB.NET dll that I wan't to be checked by default. There is a total of 3 radio buttons in this group. Under its properties I set Checked = true. I verified the code was there, this is all the form generated code for the radio button:
Me.rdbProductPC.AutoSize = True
Me.rdbProductPC.Checked = True
Me.rdbProductPC.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdbProductPC.Location = New System.Drawing.Point(49, 12)
Me.rdbProductPC.Name = "rdbProductPC"
Me.rdbProductPC.Size = New System.Drawing.Size(45, 17)
Me.rdbProductPC.TabIndex = 1
Me.rdbProductPC.TabStop = True
Me.rdbProductPC.Text = "P&&C"
Me.rdbProductPC.UseVisualStyleBackColor = True
For some reason I get this error when I start the application:
An error occurred creating the form. See Exception.InnerException for details. The error is: ExecuteReader requires an open and available Connection. The connection's current state is closed.
Nothing has changed besides the one line adjusting the checked value. Any idea what could be causing this?
This is the code for my GetProducts() method. The error arises after the call to ExecuteReader() but I cannot see the code for this. If my g_strSQL = pc_mis_busunit_product_relate_summary it executes fine. But when g_strSQL = pc_mis_busunit_product_relate_summary '','','N' it errors out.
That being said, if I leave the radio button unchecked by default and then check it later while the program is running it will go into this same method and g_strSQL will look like pc_mis_busunit_product_relate_summary '','','N' and it will work fine.
Private Sub GetProducts(ByVal ProductList As ListBox)
Dim g_strSQL As String
ProductList.Items.Clear()
lstProductSel.Items.Clear()
lstProduct.Enabled = True
g_strSQL = String.Empty
objcmd.Connection = ControlConnection
'Clear location combo box
Select Case intProduct
Case Product.Summary
g_strSQL = g_strSQL & "pc_mis_busunit_product_relate_summary "
Case Product.Detail
g_strSQL = "SELECT DISTINCT b.dtl_prod_cd, rtrim(ltrim(b.dtl_prod_desc))"
g_strSQL = g_strSQL & " FROM product_detail_ref b "
g_strSQL = g_strSQL & " ORDER BY rtrim(ltrim(b.dtl_prod_desc)) "
Case Else
Exit Sub
End Select
If p_and_C <> String.Empty Then
g_strSQL = g_strSQL & "'" & String.Empty & "','" & String.Empty & "','" & p_and_C & "'"
End If
If g_strSQL <> "" Then
objcmd.CommandText = g_strSQL
rsProducts = objcmd.ExecuteReader()
End If
'Process results from query
If rsProducts.HasRows = False Then
rsProducts.Close()
Exit Sub
Else
' This nested if will check which radio button is selected and add the corresponding
' 'all' entry to the top of the lstProduct box
If rdbProductPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_P_AND_C)
ElseIf rdbProductNonPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_NON_P_AND_C)
Else
ProductList.Items.Add(PAndCConstants.ALL)
End If
ProductList.SelectedIndex = 0
While rsProducts.Read()
ProductList.Items.Add(rsProducts(0))
End While
ProductList.SetSelected(0, True)
rsProducts.Close()
End If
rsProducts = Nothing
End Sub
Okay so for an internship project i'm making a Journal with streamwriters and streamreaders.
I have to to where you can create an account with a name, Username, and Password. I also have it to where it creates a txt file in that persons name when you create the account. Now, they login and it brings them to the journal page. The Journal Page for the most part has a Date for your journal Entry, the title of the journal and the journal entry text itself.
The problem that I am having is that when you click the button to create/edit a journal entry, it goes through a sub routine that checks if that journal exists (Meaning that there is already one for that date) or not. If it doesn't exist, then it should create a new one at the bottom of the text file. If it does exist then it should edit the lines in which that journal are stationed in the text file.
Code:
Private Sub CreateBtn_Click(sender As System.Object, e As System.EventArgs) Handles CreateBtn.Click
Errors = ""
Dim TempCounter As Integer = 0
If TitleTxt.Text = "" Then
Errors = "You must enter a title." & vbCrLf
End If
If JournalTextRtxt.Text = "" Then
Errors &= "You must enter an entry for the journal."
End If
If Errors <> "" Then
MessageBox.Show("There's an error in creating/editing your journal." & vbCrLf & "Error(s):" & vbCrLf & Errors, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(TempCounter).TheDate = JournalDate
arrJournalEntries(TempCounter).Title = JournalTitle
arrJournalEntries(TempCounter).JournalEntry = JournalText
CheckAndWrite()
End If
End Sub
Private Sub CheckAndWrite()
Dim Reader As New StreamReader(MyName & ".txt", False)
Dim Sline As String = Reader.ReadLine
Counter = 0
Do Until (Sline Is Nothing) 'Perform the code until the line in the text file is blank
If Not Sline Is Nothing Then 'If the line in the text file is NOT blank then
For i As Integer = 1 To 3
Select Case i
Case 1
arrJournalEntries(Counter).TheDate = Sline
Sline = Reader.ReadLine
Case 2
arrJournalEntries(Counter).Title = Sline
Sline = Reader.ReadLine
Case 3
arrJournalEntries(Counter).JournalEntry = Sline
Sline = Reader.ReadLine
End Select
Next
End If
JournalDate = arrJournalEntries(Counter).TheDate
Time = DateTimePicker1.Value
MsgBox("Journal Date = " & JournalDate & vbCrLf & "Today's Date = " & Time)
If Time = JournalDate Then
JournalFound = True
Else
Counter += 1
JournalFound = False
End If
Loop
Reader.Close()
Try
If Sline Is Nothing Or JournalFound = False Then
MsgBox("Your journal is now going to be created.")
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(Counter).TheDate = JournalDate
arrJournalEntries(Counter).Title = JournalTitle
arrJournalEntries(Counter).JournalEntry = JournalText
Dim Writer As New StreamWriter(MyName & ".txt", True)
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
Counter += 1
Loop
Writer.Close()
End If
If JournalFound = True Then
MsgBox("Your journal is now going to be edited.")
JournalDate = DateTimePicker1.Value
JournalTitle = TitleTxt.Text
JournalText = JournalTextRtxt.Text
arrJournalEntries(Counter).TheDate = JournalDate
arrJournalEntries(Counter).Title = JournalTitle
arrJournalEntries(Counter).JournalEntry = JournalText
Dim Writer As New StreamWriter(MyName & ".txt", True)
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
Counter += 1
Loop
Writer.Close()
End If
Catch ex As Exception
MessageBox.Show("An error has occured" & vbCrLf & vbCrLf & "Original Error:" & vbCrLf & ex.ToString)
End Try
End Sub`
The problem that's occuring is that it's not only writing in the first time wrong. When it's supposed to say it's going to edit, it doesn't, it just says creating. But it just adds on to the file. After pressing the button 3 times with the current date. and the Title being "Test title", and the journal entry text being "Test text". This is what occured.
It should just be
7/10/2012 3:52:08 PM
Test title
Test text
7/10/2012 3:52:08 PM
Test title
Test text
the whole way through. but of course if it's the same date then it just overwrites it. So can anybody please help me?
You are only filtering your array by the date, so it looks like you have an object with a date but no title or text:
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
The "quick" fix:
Do Until (arrJournalEntries(Counter).TheDate = Nothing)
If arrJournalEntries(Counter).Title <> String.Empty Then
Writer.WriteLine(arrJournalEntries(Counter).TheDate)
Writer.WriteLine(arrJournalEntries(Counter).Title)
Writer.WriteLine(arrJournalEntries(Counter).JournalEntry)
End If
Counter += 1
Loop
Do consider getting rid of the array and using a List(of JournalEntry) instead. Your code looks difficult to maintain in its current state.