Null Exception while loading my file to listbox. - vb.net

I have a problem. I'm trying to load data to listbox , but when I click start I get an unhandled exception that states values cannot be null. I've bolded where the issue is.
I'm trying to create a library database, and would really appreciate if someone could help me fix this issue. Thanks!
Public Class frmLibrary
Structure BookData
Dim Title As String
Dim Author As String
Dim ISBN As Integer
Dim YearPublished As Integer
End Structure
Dim bookinfo() As BookData 'Array
Private Sub frmLibrary_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim bookfiles() As String = IO.File.ReadAllLines("LibraryDatabase.txt")
Dim n As Integer = bookfiles.Count - 1
ReDim bookinfo(n)
Dim line As String
Dim books() As String 'books are the parts
'use the split methods to assign values to the members of the structure variable.
For i As Integer = 0 To n ---**>Why is this value null???????**
line = bookfiles(i)
books = line.Split(","c) '
bookinfo(i).Title = books(0)
bookinfo(i).Author = books(1)
bookinfo(i).ISBN = books(2)
bookinfo(i).YearPublished = books(3)
Next
Dim query = From book In bookinfo
Select book.Title, book.Author, book.ISBN, book.YearPublished
DGVBookInfo.DataSource = query.ToList
DGVBookInfo.Columns("Title").HeaderText = "Title"
DGVBookInfo.Columns("Author").HeaderText = "Author"
DGVBookInfo.Columns("ISBN").HeaderText = "ISBN"
DGVBookInfo.Columns("Year Published").HeaderText = "Year Published"
DGVBookInfo.AutoResizeColumns()
DGVBookInfo.RowHeadersVisible = False
End Sub

Related

calling a part of a structure into a button click

I'm relatively new to vb. I have made a structure and now I want to do a bubble sort on the values. I'm unsure on how to call all of the data in the single part of the structure which is also a list.
(module)
module module 1
structure studenttype
dim id as string
dim name as string
end structure
public studentdetails as new list(of studenttype)
(main code)
Private Function bubbleSortbyID(ByVal namelist() As String) As String()
Dim n As Integer = namelist.Length()
Dim swapped As Boolean
Do
swapped = False
For i As Integer = 1 To n - 2
If namelist(i) > namelist(i + 1) Then
Dim temp As String = namelist(i + 1)
namelist(i + 1) = namelist(i)
namelist(i) = temp
swapped = True
End If
Next
Loop Until swapped = False 'no swap made so order Is correct
Return namelist
End Function
Private Sub BtnSort_Click(sender As Object, e As EventArgs) Handles BtnSort.Click
Dim id As String ' it is here I do not how how to call the whole variable
bubbleSortbyID(id)' id remains empty
ClearAndAdd()
End Sub'''

Currently having problems with deleting/overwriting from a file

I'm currently having problems trying to delete a line from a file and replace that line with different text (overwrite the line)
The code initially starts by extracting file contents to find the
DepartmentDetails which can be used to find DepartmentBudget and subtract AmountDue and then create a new DepartmentDetails with the new budget
Once this is complete the code will add the N̳e̳w̳ DepartmentDetails which will leave the code with having the O͟l͟d͟ and the N̳e̳w̳ DepartmentDetails in the same folder.
The code should then delete the O͟l͟d͟ DepartmentDetails from the file making the N̳e̳w̳ DepartmentBudget take it's place. i.e. Overwrite the O͟l͟d͟ DepartmentDetails with the new one.
The problem is that the code does not delete the O͟l͟d͟ DepartmentBudget but adds a line space in between the O͟l͟d͟ and N̳e̳w̳ instead.
Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
Dim DepartmentStore As New Department
Dim Order() As String = File.ReadAllLines(Dir$("OrderDetails.Txt"))
Dim OrderID As String = TxtOrderID.Text
Dim AmountDue As String = TxtAmountDue.Text
Dim DeptID As String = (Trim(Mid(Order(OrderID), 5, 4)))
Dim DepartmentDetails() As String = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))
Dim DepartmentBudget As String = (Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
Dim YesNo As String
Dim sw As New StreamWriter("DepartmentDetails.txt", True)
DepartmentBudget = FormattedBudget - AmountDue
DepartmentStore.DepartmentID = LSet(DeptID, 4)
DepartmentStore.DepartmentHead = LSet((Trim(Mid(DepartmentDetails(DeptID), 5, 20))), 20)
DepartmentStore.DepartmentName = LSet((Trim(Mid(DepartmentDetails(DeptID), 25, 10))), 10)
DepartmentStore.DepartmentBudget = LSet(DepartmentBudget, 9)
DeptID = UBound(DepartmentDetails)
DepartmentDetails(DeptID) = ""
File.WriteAllLines("DepartmentDetails", DepartmentDetails)
sw.WriteLine(DepartmentStore.DepartmentID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & DepartmentStore.DepartmentBudget)
sw.Close()`
'***********************Having Problems Here***********************
DepartmentDetails = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))
DepartmentDetails(DeptID) = ""
File.WriteAllLines("DepartmentDetails", DepartmentDetails)
'************************Having Problems Here**************************
YesNo = MsgBox("Department has been billed. Would you like to delete the bill?", vbYesNo)
If YesNo = vbYes Then
End If
End Sub
Who decided that this text file would be formatted with fixed length fields? All this trimming and padding could be avoided with a simple comma delimited file or an xml file or a database where it really belongs.
Code is not tested. Comments and explanations in-line.
'I assume you have a class that looks something like this
'This uses automatic properties to save you having to
'type a getter, setter and backer field (the compiler adds these)
Public Class Department
Public Property DepartmentID As Integer
Public Property DepartmentHead As String
Public Property DepartmentName As String
Public Property DepartmentBudget As Decimal
End Class
Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
Dim DepartmentStore As New Department
'Drag an OpenFileDialog from the ToolBox to your form
'It will appear in the lower portion of the design window
Dim MyFilePath As String = ""
OpenFileDialog1.Title = "Select OrderDetails.Txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim Order() As String = File.ReadAllLines(MyFilePath)
'Changed data type, you use OrderID as an index for the Order array so it must be an Integer
Dim OrderID As Integer
'TryParse will check if you have a valid interger and fill OrderID variable
If Not Integer.TryParse(TxtOrderID.Text, OrderID) Then
MessageBox.Show("Please enter a valid Order ID.")
Return
End If
'EDIT per comment by Codexer
If OrderID > Order.Length - 1 Then
MessageBox.Show("Order Number is too high")
Return
End If
Dim AmountDue As Decimal
If Decimal.TryParse(TxtAmountDue.Text, AmountDue) Then
MessageBox.Show("Please enter a valid Amount Due")
Return
End If
'I hope you realize that the first index in Order is zero
'Mid is an old VB6 method around for compatibility
'Use the .net Substring (startIndex As Integer, length As Integer)
'The indexes in the string start with zero
Dim DeptID As Integer = CInt(Order(OrderID).Substring(5, 4).Trim) '(Trim(Mid(Order(OrderID), 5, 4)))
OpenFileDialog1.Title = "Select DepartmentDetails.txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim DepartmentDetails() As String = File.ReadAllLines(MyFilePath)
Dim DepartmentBudget As Decimal = CDec(DepartmentDetails(DeptID).Substring(35, 6).Trim) '(Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
'You don't need to format anything until you want to display it
'Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
'A MessageBox returns a DialogResult
Dim YesNo As DialogResult
Dim sw As New StreamWriter(MyFilePath, True)
'Shorcut way to write DepartmentBudget - AmountDue
DepartmentBudget -= AmountDue
'Set the property in the class with the proper data type
DepartmentStore.DepartmentID = DeptID
'Then prepare a string for the writing to the fil
Dim PaddedID = CStr(DeptID).PadLeft(4)
'The .net replacement for LSet is .PadLeft
DepartmentStore.DepartmentHead = DepartmentDetails(DeptID).Substring(5, 20).Trim.PadLeft(20)
DepartmentStore.DepartmentName = DepartmentDetails(DeptID).Substring(25, 10).Trim.PadLeft(20)
'Set the property in the class with the proper data type
DepartmentStore.DepartmentBudget = DepartmentBudget
'Then prepare a string for the writing to the fil
Dim PaddedBudget = CStr(DepartmentBudget).PadLeft(9)
sw.WriteLine(PaddedID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & PaddedBudget)
sw.Close()
'***********************Having Problems Here***********************
'This is using the path from the most recent dialog
DepartmentDetails = File.ReadAllLines(MyFilePath)
'Here you are changing the value of one of the elements in the DepartmentDetails array
DepartmentDetails(DeptID) = ""
'Public Shared Sub WriteAllLines (path As String, contents As String())
'The string "DepartmentDetails" is not a path
File.WriteAllLines(MyFilePath, DepartmentDetails)
'************************Having Problems Here**************************
YesNo = MessageBox.Show("Department has been billed. Would you like to delete the bill?", "Delete Bill?", MessageBoxButtons.YesNo)
If YesNo = DialogResult.Yes Then
End If
End Sub

How to Replace string and loop between commas with another string

can you help me how to get Index of the same string and replace it one by one with another string?
Here my example code :
For i As Integer = 0 To 10
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
Dim value As String
value = str.Replace("abcd", replace)
TextBox4.AppendText(value)
Next
The value will be result : efgh,efgh,efgh,efgh,efgh...
How i can create the result like this :
efgh,abcd,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,efgh,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,abcd,efgh,abcd,abcd,abcd...
Thank you
There are lots of ways this could be done. One perhaps inefficient way would be to split the string at the commas, replace the appropriate item in the resulting array, and then join the array back up.
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
For i As Integer = 0 To str.Count(Function(x) x = ","c)
Dim strParts = str.Split(","c)
strParts(i) = replace
Dim value As String = String.Join(",", strParts)
Console.WriteLine(value)
Next
Output:
efgh,abcd,abcd,abcd,abcd,abcd,abcd,abcd
abcd,efgh,abcd,abcd,abcd,abcd,abcd,abcd
abcd,abcd,efgh,abcd,abcd,abcd,abcd,abcd
abcd,abcd,abcd,efgh,abcd,abcd,abcd,abcd
abcd,abcd,abcd,abcd,efgh,abcd,abcd,abcd
abcd,abcd,abcd,abcd,abcd,efgh,abcd,abcd
abcd,abcd,abcd,abcd,abcd,abcd,efgh,abcd
abcd,abcd,abcd,abcd,abcd,abcd,abcd,efgh
As #Mark mentioned there are lots of ways this could be done. One of this ways to add and remove ranges in a string is to use the StringBuilder.
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 35 Step 5
Dim sDefaultString As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim sbText = New StringBuilder(sDefaultString)
sbText.Remove(i, 4)
sbText.Insert(i, "efgh")
TextBox1.AppendText(sbText.ToString & vbNewLine)
Next
End Sub
End Class

Visual Basic Confusion

I have been required to create a program that asks me to find the maximum value of one particular array. I am using multiple forms in this project and have used a user-defined data type and created multiple array under it. There is a first form that is related to this, which defines my defined data type is gStudentRecord and the arrays that define it are last name, Id, and GPA. This second form is where I write all of the code to display what I want. My question is how to get the Max GPA out of that array. I'm sorry if this isn't in very good format, this is the first time I've used Stackoverflow
Public Class frmSecond
Private Sub frmSecond_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Ctr As Integer
Dim Line As String
lstDisplay.Items.Clear()
lstDisplay.Items.Add("Name".PadRight(25) & "ID".PadRight(16) & "GPA".PadRight(20) & "Out of state".PadRight(10))
For Ctr = 0 To gIndex Step 1
Line = gCourseRoster(Ctr).LastName.PadRight(20) & gCourseRoster(Ctr).ID.PadRight(15) & gCourseRoster(Ctr).GPA.ToString.PadRight(15) & gCourseRoster(Ctr).OutOfState.ToString().PadLeft(5)
lstDisplay.Items.Add(Line)
Next
End Sub
Private Sub btnStats_Click(sender As Object, e As EventArgs) Handles btnStats.Click
Dim Ctr As Integer = 0
Dim Average As Double
Dim Sum As Double
Dim Found As Boolean = False
Dim Pass As Integer
Dim Index As Integer
lstDisplay.Items.Clear()
**For Ctr = 0 To gIndex Step 1
If gCourseRoster(Ctr).GPA > gCourseRoster(Ctr).GPA Then
lstDisplay.Items.Add(gCourseRoster(Ctr).GPA)
End If
Next**
Average = gComputeAverage(Sum)
lstDisplay.Items.Add("Number of Students: " & gNumberOfStudents)
lstDisplay.Items.Add("Average: " & Average)
End Sub
Private Function gComputeAverage(Sum As Double) As Double
Dim Ctr As Integer
Dim Average As Double
For Ctr = 0 To gIndex Step 1
Sum = Sum + gCourseRoster(Ctr).GPA
Next
Average = Sum / gNumberOfStudents
Return Average
End Function
End Class
You can use a Lambda expression to tease it out. The Cast part is converting from the gCourseRoster to a collection of Double by supplying the GPA to the Select statement.
Dim gList As New List(Of gCourseRoster)
gList.Add(New gCourseRoster With {.id = 1, .name = "Bob", .GPA = 3.9})
gList.Add(New gCourseRoster With {.id = 2, .name = "Sarah", .GPA = 3.2})
gList.Add(New gCourseRoster With {.id = 3, .name = "Frank", .GPA = 3.1})
Dim maxGPA = gList.Cast(Of gCourseRoster).Select(Function(c) c.GPA).ToList.Max
MessageBox.Show(maxGPA.ToString)
Output: 3.9

Send text from textboxes to datagrid

I have for textboxes on my form and I would like the text there to be send to a datagrid. I wrote the following:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim itemName As String = txtItem.Text
Dim qty As Double = CDbl(txtQTY.Text)
Dim price As Double = CDbl(txtPrice.Text)
Dim Total As Double = price * qty
txtTotal.Text = Convert.ToString(Total)
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As TextBox() = New TextBox() {txtItem, txtQTY, txtPrice, txtTotal}
grdNewInvoice.Rows.Add()
For i As Integer = 0 To data.Length - 1
grdNewInvoice(i, row).Value = data(0)
Next
End Sub
But I get the following on my datagrid row: System.Windows.Forms.TextBox, Text: [textbox string]
I tried the following code as well to make sure there was nothing wrong with my settings on my datagrid:
'grdNewInvoice.Rows(0).Cells(0).Value = itemName
'grdNewInvoice.Rows(0).Cells(1).Value = qty
'grdNewInvoice.Rows(0).Cells(2).Value = price
'grdNewInvoice.Rows(0).Cells(3).Value = Total
That worked fine and the text went in as expected but since I will be writing to multiple lines on the datagrid, I will need to use a loop.
What am I doing wrong here?
One way to do this is to use a list of string array.
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As New List(Of String())
data.Add({txtItem.Text, txtQTY.Text, txtPrice.Text, txtTotal.Text})
data.Add({"Item2", "qtr2", "price2", "total2"})
data.Add({"Item3", "qty3", "price3", "total3"})
For i As Integer = 0 To data.Count - 1
grdNewInvoice.Rows.Add(data(i))
Next