System.IndexOutOfRangeException VB GradeBook - vb.net

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.

Related

The last if statement will not be executed when the conditions of the list are met?

Console.WriteLine("Welcome to the game noughts and crosses")
While game = 1
While gameplay = 0
Console.WriteLine("Please choose a square to place X")
move = Console.ReadLine
If row(move - 1) = " " Then
row(move - 1) = row(move - 1).Replace(CChar(" "), CChar("X"))
gameplay = 1
count = count + 1
Else
Console.WriteLine("That space has already been taken")
Console.ReadLine()
End If
Console.WriteLine(row(0) & row(1) & row(2))
Console.WriteLine(row(3) & row(4) & row(5))
Console.WriteLine(row(6) & row(7) & row(8))
Console.ReadLine()
End While
While gameplay = 1
npcmove = (10 * Rnd())
If row(npcmove - 1) = " " Then
row(npcmove - 1) = row(npcmove - 1).Replace(CChar(" "), CChar("O"))
gameplay = 0
count = count + 1
Console.WriteLine("The CPU has chosen to place O in space " & npcmove)
Else
Console.WriteLine("That space has already been taken")
Console.ReadLine()
End If
Console.WriteLine(row(0) & row(1) & row(2))
Console.WriteLine(row(3) & row(4) & row(5))
Console.WriteLine(row(6) & row(7) & row(8))
Console.ReadLine()
End While
End While
End Sub
Sub endgame()
If count = 9 Then
Console.WriteLine("The game was a tie")
Console.ReadLine()
FileClose()
End If
End Sub
Sub VicRoy()
If (row(0).Contains("X") & row(1).Contains("X") & row(2).Contains("X")) Then
Console.WriteLine("Congratulations on the epic Victory Royale")
Console.ReadLine()
FileClose()
End If
The code runs a noughts and crosses game with a random ai using while loops. The board is represented via a new list of strings. However once I meet the condition of the if statement, where all the values are X the if statement will not be executed and the game will continue
replace & with And, the & in vb.net mean you just will Merage strings

Value Of Type Form1.Data cannot be converted to Form1.Data() when passing parameters

At the start of the program I define a new Public Structure 'Data':
Public Structure Data
Dim car, grid, points As String
Dim driver, team, fastestlap, racetime As String
End Structure
I then have the user input data and it is added to array displayData(5) of data type 'Data'.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim displayData(5) As Data
Dim accepted As Boolean = False
Dim temp As String
Dim tempNum As Integer
Dim output As String = ""
Dim arraysize As Integer = 0
For x = 0 To 5
displayData(x).driver = InputBox("Please enter the name of driver number " & x + 1)
temp = InputBox("Please enter the car number of driver number " & x + 1)
While accepted = False
If IsNumeric(temp) Then
accepted = True
displayData(x).car = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the car number of driver number " & x + 1)
End If
End While
accepted = False
displayData(x).team = InputBox("Please enter the team name of driver number " & x + 1)
temp = InputBox("Please enter the grid number of driver number " & x + 1)
tempNum = Convert.ToInt32(temp)
While accepted = False
If IsNumeric(tempNum) Then
accepted = True
displayData(x).grid = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the grid number of driver number " & x + 1)
tempNum = Convert.ToInt32(temp)
End If
End While
accepted = False
displayData(x).fastestlap = InputBox("Please enter the fastest lap of driver number " & x + 1)
displayData(x).racetime = InputBox("Please enter the race time of driver number " & x + 1)
temp = InputBox("Please enter the points of driver number " & x + 1)
While accepted = False
If IsNumeric(temp) Then
accepted = True
displayData(x).points = temp
Else
accepted = False
temp = InputBox("Error: integer not entered. Please enter the points of driver number " & x + 1)
End If
End While
accepted = False
output = output & displayData(x).driver & "," & displayData(x).car & "," & displayData(x).team & "," & displayData(x).grid & "," & displayData(x).fastestlap & "," & displayData(x).racetime & "," & displayData(x).points & vbCrLf
Next
Dim filename As String = "U:\Subjects\Computing\AH Computing\Project Files\Leaderboard.csv"
My.Computer.FileSystem.WriteAllText(filename, output, True)
bubbleSort(arraysize, displayData(6))
End Sub
Above is the main bulk of my code. I am getting an error from typing in displayData(6) into bubblesort, which is defined here:
Public Sub bubbleSort(ByVal arraysize As Integer, ByVal displayData() As Data)
Dim counter As Integer
Dim outerloop As Integer
For outerloop = (arraysize - 2) To 0 Step -1
For counter = 0 To outerloop
If displayData(counter).racetime > displayData(counter + 1).racetime Then
swap(displayData(counter).racetime, displayData(counter + 1).racetime)
swap(displayData(counter).car, displayData(counter + 1).car)
swap(displayData(counter).driver, displayData(counter + 1).driver)
swap(displayData(counter).points, displayData(counter + 1).points)
swap(displayData(counter).team, displayData(counter + 1).team)
swap(displayData(counter).fastestlap, displayData(counter + 1).fastestlap)
swap(displayData(counter).grid, displayData(counter + 1).grid)
End If
Next
Next
End Sub
And apparently I need more normal text in order to save this. The bubble sort uses a swap algorithm that I defined in another part of the program, but it is incredibly simple and is 100% not the cause of the error so it seems unproductive to include it.

Returning values from array separately

I am looking for a way to return the type of bill rate with the highest reimbursement rate.
Of the three variables that I am searching against, I'd like to store the name of the variable returned to the table so that users can determine which billing type was used.
This code pulls the billing rates from the database.
CenterAllRate = DLookup("CenterBillRateAllVendors", "Centers", "CenterID = " & Chr(34) & CenterID & Chr(34))
CenterHospitalRate = DLookup("CenterBillRateHospitalOnly", "Centers", "CenterID = " & Chr(34) & CenterID & Chr(34))
VendorRate = DLookup("VendorReimbRate", "Vendors", "VendorID = " & Chr(34) & Me.Parent.VendorID & Chr(34))
ReimbursementRate = MaxOfList(CenterAllRate, CenterHospitalRate, VendorRate)
I am using this prebuilt function that I found online to find the highest reimbursement rate of the three options.
Function MaxOfList(ParamArray varValues()) As Variant
Dim i As Integer 'Loop controller.
Dim varMax As Variant 'Largest value found so far.
varMax = Null 'Initialize to null
For i = LBound(varValues) To UBound(varValues)
If IsNumeric(varValues(i)) Or IsDate(varValues(i)) Then
If varMax >= varValues(i) Then
'do nothing
Else
varMax = varValues(i)
End If
End If
Next
MaxOfList = varMax
End Function
How can I return either the name of the variable with the highest value, or give them aliases to use when creating the record?
Since you are a coding newbie, it's a good opportunity to dig a bit deeper. :)
I would create an object to wrap the Name and Rate properties and pass this to my function.
An example:
A simple Reimbursement Class:
Option Explicit
Private name_ As String
Private rate_ As Variant
Public Property Get Name() As String
Name = name_
End Property
Public Property Let Name(Value As String)
name_ = Value
End Property
Public Property Get Rate() As Variant
Rate = rate_
End Property
Public Property Let Rate(Value As Variant)
rate_ = Value
End Property
Your method with a few minor changes:
Function MaxOfList(varValues As Variant) As Reimbursement
Dim i As Integer 'Loop controller.
Dim varMax As Reimbursement 'Largest value found so far.
Set varMax = New Reimbursement
For i = LBound(varValues) To UBound(varValues)
If IsNumeric(varValues(i).Rate) Or IsDate(varValues(i).Rate) Then
If varMax.Rate < varValues(i).Rate Then
With varMax
.Name = varValues(i).Name
.Rate = varValues(i).Rate
End With
End If
End If
Next
Set MaxOfList = varMax
End Function
Lastly, to call and test it:
Sub T()
Dim centerAll As New Reimbursement
Dim centerHospital As New Reimbursement
Dim vendor As New Reimbursement
Dim maxReimbursement As New Reimbursement
With centerAll
.Name = "centerAll"
'.Rate = DLookup("CenterBillRateAllVendors", "Centers", "CenterID = " & Chr(34) & CenterID & Chr(34))
.Rate = 3
End With
With centerHospital
.Name = "centerHospital"
'.Rate = DLookup("CenterBillRateHospitalOnly", "Centers", "CenterID = " & Chr(34) & CenterID & Chr(34))
.Rate = 8
End With
With vendor
.Name = "vendor"
'.Rate = DLookup("VendorReimbRate", "Vendors", "VendorID = " & Chr(34) & Me.Parent.VendorID & Chr(34))
.Rate = 5
End With
Set maxReimbursement = MaxOfList(Array(centerAll, centerHospital, vendor))
Debug.Print maxReimbursement.Name, maxReimbursement.Rate
End Sub
'Output
'centerHospital 8
Welcome to SO.
I designed a poor solution that may work fork you, but it works under some specific conditions:
You must call always your function using same order as your example, this means you must invoke always typing MaxOfList(CenterAllRate, CenterHospitalRate, VendorRate)
My solution just stores in a variable the name of your variable used when you call your function. If you use it with another variables, it will not update. This means that, if your example, you invoke the function with other variables, like MaxOfList(AnotherAllRate, DifferentAllRate, ExampleRate) my solution won't return the right name. It just works with CenterAllRate, CenterHospitalRate, VendorRate
Ok, after this here is my poor solution. I declared a Public String var to store the name of the Highest of the list called HighestVar. This var updates every time you call function MaxofList
Option Explicit
Public HighestVar As String 'We declare the public Var to store name of max rate
Function MaxOfList(ParamArray varValues()) As Variant
Dim i As Integer 'Loop controller.
Dim varMax As Variant 'Largest value found so far.
HighestVar = "" 'We Reset the var
varMax = Null 'Initialize to null
For i = LBound(varValues) To UBound(varValues)
If IsNumeric(varValues(i)) Or IsDate(varValues(i)) Then
If varMax >= varValues(i) Then
'do nothing
Else
varMax = varValues(i)
Select Case i 'We use select Case to store in HighestVar the name of highest rate
Case 0
HighestVar = "CenterAllRate"
Case 1
HighestVar = "CenterHospitalRate"
Case 2
HighestVar = "VendorRate"
End Select
End If
End If
Next
MaxOfList = varMax
End Function
Every time you call function MaxofList then you'll have in var HighestVar the name of the highest rate. Just use it where you want it. For example:
CenterAllRate = DLookup("CenterBillRateAllVendors", "Centers", "CenterID = " & Chr(34) & CenterID & Chr(34))
CenterHospitalRate = DLookup("CenterBillRateHospitalOnly", "Centers", "CenterID = " & Chr(34) & CenterID & Chr(34))
VendorRate = DLookup("VendorReimbRate", "Vendors", "VendorID = " & Chr(34) & Me.Parent.VendorID & Chr(34))
ReimbursementRate = MaxOfList(CenterAllRate, CenterHospitalRate, VendorRate)
Msgbox HighestVar & " is the highest rate" 'We show in Msgbox highest rate
Hope this can help you. Let me know.

how to order a text file without using array and query

I'm trying to order a text file which contain numbers and rewrite it in other textile without using query of array
i try to do it using a comparing statement but in the end it only write one number in the new text file
to make it clear the program is to find the median number in that file which is something i can't do without reordering the file descending or ascending
This is what i did
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sw As IO.StreamReader = IO.File.OpenText("Numbers.txt")
Dim sr As IO.StreamWriter = IO.File.CreateText("Numbers2.txt")
Dim num As Double
Dim min As Double = CDbl(sw.ReadLine)
Dim line As String = sw.ReadLine
Do Until sw.EndOfStream
num = CDbl(sw.ReadLine)
If min > num Then
sr.WriteLine(num)
End If
Loop
sr.Close()
End Sub
Well, of curse I have no idea how your text file looks, I can't help without his string format
So I made two functions who will help about the median program
the program is to find the median number in that file
You can test this code just add 1 button in a frame that's all (I wrote some strings for test, you can change it)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Button1.Text = "20; 30; 50; 40; 10; 80; 90; 70" Then 'A pair list of simple numbers
Button1.Text = "20; 30; 50; 40; 80; 90; 70" 'Odd list of simple numbers
Else
If Button1.Text = "20; 30; 50; 40; 80; 90; 70" Then
Button1.Text = "18; 91,123; 47,789; 29; 35; 78.456; 91; 84" 'A test with a mix of some decimal separators mistakes
Else
If Button1.Text = "18; 91,123; 47,789; 29; 35; 78.456; 91; 84" Then
Button1.Text = "25.45; 78; 10.123; 65; 27.485; 78; 19; 41; 26" 'Another odd test
Else
Button1.Text = "20; 30; 50; 40; 10; 80; 90; 70"
End If
End If
End If
Dim StringList As String = Button1.Text
Me.Text = "Medan of " & StringList & " = " & MedianOf(StringList, "; ") 'Using "; " (; + space) separator (can be changed)
End Sub
Private Function MedianOf(ByVal StrLine As String, ByVal Separator As String) As Double
Dim Nb As Double
Dim Str As String = StrLine
'Write all values in the good order with the next function down here e.g.(from "23; 12; 78; ..." to "12; 23; 78; ...")
StrLine = GetOrderOf(StrLine, Separator)
'Counts how many values StrLine contains
Dim ValuesInString = System.Text.RegularExpressions.Regex.Split(StrLine, "\" & Separator).GetUpperBound(0) + 1
'Check ValuesInString count odd's (calculated with different ways)
If ((ValuesInString And 1) = 1) = True Then
Nb = CDbl(System.Text.RegularExpressions.Regex.Split(StrLine, "\" & Separator)(ValuesInString \ 2))
MessageBox.Show("ODD:" & Environment.NewLine & "First String = " & Str & Environment.NewLine & "Ordered string = " & StrLine & Environment.NewLine & "*** Median value = " & Nb & " ***")
Else
Nb = (CDbl(System.Text.RegularExpressions.Regex.Split(StrLine, "\" & Separator)((ValuesInString / 2) - 1)) + CDbl(System.Text.RegularExpressions.Regex.Split(StrLine, "\" & Separator)(ValuesInString / 2))) / 2
MessageBox.Show("PAIR:" & Environment.NewLine & "First String = " & Str & Environment.NewLine & "Ordered string = " & StrLine & Environment.NewLine & "(" & StrLine.Split(Separator)((ValuesInString / 2) - 1) & "+" & StrLine.Split(Separator)(ValuesInString / 2) & ")/2 = " & Nb)
End If
'MessagesBoxes were added only for a best understanding of how it works
'Should be disabled if tests are ok
Return Nb
End Function
Private Function GetOrderOf(ByVal Line As String, ByVal Separator As String) As String
If Separator = "." Or Separator = "," Then MessageBox.Show("Wrong... so Wrong separator")
Line = Line.Replace(".", ",")
Dim Line_InOrder As String = ""
Dim Str As String = ""
Dim Nb As Double = 0
Do While Line.Length > 0
Nb = 0
If Line.Contains(Separator) Then
For Each St As String In System.Text.RegularExpressions.Regex.Split(Line, "\" & Separator)
If CDbl(St) > Nb Then
Nb = CDbl(St)
Str = St
End If
Next
Else
Str = Line
Line &= Separator
End If
If Line.Contains(Str & Separator) Then
Line = Replace(Line, Str & Separator, "", , 1)
Else
Line = Replace(Line, Separator & Str, "", , 1)
End If
If Line_InOrder.Length = 0 Then
Line_InOrder = Str
Else
Line_InOrder = Str & Separator & Line_InOrder
End If
Loop
Return Line_InOrder
End Function

loop of data within datagridview column in vb.net

i'm new in vb and can't solve this problem of mine. I have this column from datagridview mark with red box:
And from the above image i want an output like this:
Team Edna - Esca, Adarayan, Dianne, //first shout
Team Edna - Esca, Bacalla, Catherine //2nd shout and so on..
Team Aennah, Aquino, Juan Benigno //3rd shout
Team Aennah, Aguila, Mailebeth //4rth shout and so on..
I already had the code that code detech if the string is starting with "TEAM" it just the discrepancy in the wanted output. Here's my code so far:
For i As Integer = 1 To Me.DataGridView1.Rows.Count
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow Then
If InStr(row.Cells(0).Value.ToString.ToUpper, UCase(Trim("TEAM"))) <> 0 Then
team = row.Cells(0).Value.ToString.ToUpper
MessageBox.Show(team)
teamMembers = Me.DataGridView1.Rows(i).Cells(0).Value.ToString()
MessageBox.Show(team + ", " + teamMembers)
End If
End If
Next
Next
And the output of this was:
Team Edna - Esca, Adarayan, Dianne
Team Aennah, Adarayan, Dianne
Team Edna, Bacalla, Catherine
Team Aennah, Bacalla, Catherine //so on..
Please help my guys.
try this.. : replace your code ,
Dim team, groups, teamMembers As String
Dim _counter As Integer = 0
For _xdtRow As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(_xdtRow).Cells(0).Value.ToString.Contains("Team") = True Then
team = DataGridView1.Rows(_xdtRow).Cells(0).Value.ToString
'_counter = _xdtRow
For _xrow As Integer = (_xdtRow + 1) To DataGridView1.Rows.Count - 1
_counter += 1
If DataGridView1.Rows(_xrow).Cells(0).Value.ToString.Contains("Team") = True Then
Exit For
Else
teamMembers += DataGridView1.Rows(_xrow).Cells(0).Value.ToString & ","
End If
Next
_xdtRow = _counter
groups += team & " - " & teamMembers & vbNewLine & vbNewLine
'MsgBox(groups)
team = Nothing
teamMembers = Nothing
End If
Next
Dim _perGrp As String()
_perGrp = groups.Split(New Char() {"_"c})
For Each perGrp As String In _perGrp
MsgBox(perGrp)
Next
OUTPUT:
HTH.. :)
This example ALSO includes you other items as well... you have arrays that you can play around with or send it to messagebox, richtextbox or what ever you want with it...
Private Sub btnOutput_Click(sender As Object, e As EventArgs) Handles btnOutput.Click
Dim arrTeamOne As New ArrayList
Dim arrTeamTwo As New ArrayList
Dim strMembers As New StringBuilder
Dim blnTeamOne As Boolean = False
For i As Integer = 0 To dgvMembers.Rows.Count - 1
If Not (dgvMembers.Rows(i).Index = 0) Then
If dgvMembers.Rows(i).Cells(0).Value.ToString.Contains("Team Edna - Esca") Then
Continue For
Else
If Not dgvMembers.Rows(i).Cells(0).Value.ToString.Contains("Team Aennah") Then
If Not blnTeamOne Then
arrTeamOne.Add("Team Edna - Esca, " & dgvMembers.Rows(i).Cells(0).Value.ToString & ", " & dgvMembers.Rows(i).Cells(1).Value.ToString & ", " & dgvMembers.Rows(i).Cells(2).Value.ToString)
Else
arrTeamTwo.Add("Team Aennah, " & dgvMembers.Rows(i).Cells(0).Value.ToString & ", " & dgvMembers.Rows(i).Cells(1).Value.ToString & ", " & dgvMembers.Rows(i).Cells(2).Value.ToString)
End If
Else
If dgvMembers.Rows(i).Cells(0).Value.ToString.Contains("Team Aennah") Then
blnTeamOne = True
Continue For
End If
End If
End If
End If
Next
For Each arr As String In arrTeamOne
strMembers.AppendLine(arr.ToString)
Next
For Each arr As String In arrTeamTwo
strMembers.AppendLine(arr.ToString)
Next
Messagebox.Show(strMembers.ToString)
End Sub
Here's what the output looks like...