Saving a table in VisualBasic 2010 to a .txt file - vb.net

I am looking to get the table that is generated at the end of the program below have the option to be saved into a .txt so that it can be looked back to at a later date but am struggling to get this to happen.
Module Module1
Dim kTick As Integer
Dim kName(64) As String
Dim kHours(64) As Integer
Dim kHoursPay(64) As Integer
Dim kGross(64) As Integer
Dim kTax As Integer = 20
Dim kNet(64) As Integer
Dim kTotal As Integer
Dim kAverage As Integer
Sub Main()
'Assigning kTick (Number of employee's)
Assign()
'Imputting the data
Entry()
'Calculating kGross, kTax, kNet and kTotal
Print()
End Sub
Sub Assign()
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the total amount of employee's:")
Console.ForegroundColor = ConsoleColor.White
kTick = Console.ReadLine()
Console.Clear()
End Sub
Sub Entry()
For kCounter = 1 To kTick
Console.ForegroundColor = ConsoleColor.DarkGray
Console.WriteLine("Employee " & kCounter)
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the employee name below:")
Console.ForegroundColor = ConsoleColor.White
kName(kCounter) = Console.ReadLine()
Do
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the employees total hours worked below:")
Console.ForegroundColor = ConsoleColor.White
kHours(kCounter) = Console.ReadLine()
Loop Until kHours(kCounter) >= 0 And kHours(kCounter) <= 60
Do
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Please enter the employees Hourly Pay below:")
Console.ForegroundColor = ConsoleColor.White
kHoursPay(kCounter) = Console.ReadLine()
Loop Until kHoursPay(kCounter) >= 6 And kHoursPay(kCounter) <= 250
Console.Clear()
Next
End Sub
Sub Print()
For kCounter = 1 To kTick
kGross(kCounter) = kHours(kCounter) * kHoursPay(kCounter)
Next
For kCounter = 1 To kTick
kNet(kCounter) = (kGross(kCounter) / 10) * 8
Next
For kCounter = 1 To kTick
kTotal = kTotal + kHours(kCounter)
Next
kAverage = kTotal / kTick
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Name" & vbTab & "Hours" & vbTab & "Hourly Rate" & vbTab & "Gross Pay" & vbTab & "Tax" & vbTab & "Net Pay")
Console.ForegroundColor = ConsoleColor.White
For kCounter = 1 To kTick
Console.WriteLine(kName(kCounter) & vbTab & kHours(kCounter) & vbTab & "£" & kHoursPay(kCounter) & vbTab & vbTab & "£" & kGross(kCounter) & vbTab & vbTab & kTax & "%" & vbTab & "£" & kNet(kCounter))
Next
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("Total hours worked: " & kTotal)
Console.WriteLine("Total average hours worked: " & kAverage)
Console.WriteLine("Total number of employees: " & kTick)
Console.ReadLine()
Save()
End Sub
Sub Save()
End Sub
End Module
I am trying to get the code in the Save subroutine any help will be appreciated!
Thanks Kai

One note: you should not Save from Print since both are unrelated by nature. So you may want to print without saving or save without printing to the console.
A simple approach is using the File class, for example by using File.WriteAllText(path) or File.WriteAllLines(path). Therefore you need to store the text you want to output(to the console and the file) somewhere. For example in a List(Of String) variable.

You are looking for StreamWriter class. It has Write and WriteLine methods that can help you. It works in a same way as Console.WriteLine you are using.

Related

VB.NET ComboBox selected item not remains effect than 2 times

I have a VB windows form application that has 02 ComboBox that provide newname input for a renaming file event. The first combobox provide prefix for new name comprise items (aa, bb, cc,... can add more through keydown button click event), the other combobox provide main name comprise items (XX, YY, ZZ,.. can also add more through keydown button click event). When I select "aa" from the first combobox, "XX" from the other then fire the rename event, the new file name should be "aa - XX", if file "aa - XX" has already existed then add "1" to the last as "aa - XX 1" and so on and if no item selected in prefix combobox the newname just be "XX" and increment. I get the old file name through a system openfiledialog. My code for rename as follows:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim var As String, prfix As String
var = ComboBox1.Text
prfix = ComboBox2.Text
If ComboBox2.Text = Nothing Then
If File.Exists(n & "\" & var & extn) = False Then
My.Computer.FileSystem.RenameFile(OpenFD.FileName, var & extn)
Else
Dim i As Integer = 1
Dim newfn As String = var & " " & i & extn
Dim m As String = n & "\" & newfn
While File.Exists(m)
newfn = var & " " & i & extn
m = n & "\" & newfn
i += 1
End While
My.Computer.FileSystem.RenameFile(OpenFD.FileName, newfn)
End If
Else
If File.Exists(n & "\" & prfix & " - " & var & extn) = False Then
My.Computer.FileSystem.RenameFile(OpenFD.FileName, prfix & " - " & var & extn)
Else
Dim j As Integer = 1
Dim newfn1 As String = prfix & " - " & var & " " & j & extn
Dim k As String = n & "\" & newfn1
While File.Exists(k)
newfn1 = var & " " & j & extn
k = n & "\" & newfn1
j += 1
End While
My.Computer.FileSystem.RenameFile(OpenFD.FileName, newfn1)
End If
End If
MessageBox.Show("Select a next file")
End Sub
My code run well 2 times. After I select "aa" and "XX" and leave it to rename, first result is "aa - XX", the second result is "aa - XX 1" but the third result is "XX", the forth is "XX 1" and then incrementing so on while the result should be "aa - XX 2" and next increment. I don't understand why combobox1 still effective but combobox2 as Nothing after no re-selecting the item in both comboboxes (2 times). I'm very new with VB so any advice should be much appreciated. Thanks.
In your lower Else block, you were incorrectly building up the file name.
You build up the first "newfn1" with:
Dim newfn1 As String = prfix & " - " & var & " " & j & extn
But then below, you used:
newfn1 = var & " " & j & extn
Notice the missing prefix and dash parts at the beginning.
Here's the full corrected version:
Dim j As Integer = 1
Dim newfn1 As String = prfix & " - " & var & " " & j & extn
Dim k As String = Path.Combine(n, newfn1)
While File.Exists(k)
j = j + 1
newfn1 = prfix & " - " & var & " " & j & extn
k = Path.Combine(n, newfn1)
End While
My.Computer.FileSystem.RenameFile(OpenFD.FileName, newfn1)
I'm a little confused by your explanation but if I understand correctly this should help,
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
CreateFile()
End Sub
Private BasePath As String = "" 'TODO
Private Ext As String = "txt"
Private Sub CreateFile()
If ComboBox1.SelectedIndex < 0 OrElse
ComboBox2.SelectedIndex < 0 OrElse
ComboBox1.SelectedItem.ToString = "" OrElse
ComboBox2.SelectedItem.ToString = "" Then
'error message
Exit Sub
End If
Dim fileName As String = String.Format("{0}-{1}.{2}",
ComboBox1.SelectedItem.ToString,
ComboBox2.SelectedItem.ToString,
Ext)
fileName = IO.Path.Combine(BasePath, fileName)
Dim ct As Integer = 1
Do While IO.File.Exists(fileName)
fileName = String.Format("{0}-{1}{3}.{2}",
ComboBox1.SelectedItem.ToString,
ComboBox2.SelectedItem.ToString,
Ext,
ct)
fileName = IO.Path.Combine(BasePath, fileName)
ct += 1
Loop
Dim fs As IO.FileStream = IO.File.Create(fileName)
fs.Close()
fs.Dispose()
End Sub

vba macro display result of loop to msgbox

I creted a loop checking number of characters length with conditions but sadly it's not properly working,
with approriate no. of loops but not reading the next line, I want to post the result in a MsgBox,
but when I use the msgbox inside the loop I will get a msgbox for every result found or only one msgbox with one result.
What I would like is to display every result in 1 msgbox with a line vbNewLine after each result.
Below is my code:
Public Sub Rs()
Dim Text As String
Dim NumChar As String
Dim i As Integer
Dim NumRows As Long
Application.ScreenUpdating = False
'Get Cell Value
Text = Range("B2").Value
'Get Char Length
NumChar = Len(Text)
NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
Range("B2").Select
For i = 1 To NumRows
'Character length validation
If Len(Text) <= 15 Then
MsgBox Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbNewLine
Else
MsgBox Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbNewLine
End If
Next i
Application.ScreenUpdating = True
End Sub
Assign the new text to a string variable and display the string variable outside the loop:
Option Explicit
Sub TestMe()
Dim i As Long
Dim displayText As String
For i = 1 To 3
displayText = displayText & vbCrLf & i
Next i
MsgBox displayText
End Sub
Build a string through concatenation and display the strings after exiting the loop.
Public Sub Rs()
Dim Text As String
Dim NumChar As String
Dim i As Integer
Dim NumRows As Long
dim msg1 as string, msg2 as string
Application.ScreenUpdating = False
'Get Cell Value
Text = Range("B2").Value
'Get Char Length
NumChar = Len(Text)
NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
Range("B2").Select
For i = 1 To NumRows
'Character length validation
If Len(Text) <= 15 Then
msg1 = msg1 & Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbLF
Else
msg2 = msg2 & Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbLF
End If
Next i
Application.ScreenUpdating = True
if cbool(len(msg1)) then
msg1 = left(msg1, len(msg1)-1)
MsgBox msg1
end if
if cbool(len(msg2)) then
msg2 = left(msg2, len(msg2)-1)
MsgBox msg2
end if
End Sub
A MsgBox uses Chr(10) aka vbLF for new lines; vbNewLine is overkill.

Only getting On entry for Do While Loop

I'm frustrated that I can't figure this out. Have tried few different types of loops to display a Multiplication table. All I get it one line in the label. What am I doing wrong?
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim intNum As Integer
Dim intCount As Integer
Dim intAnswer As Integer
Dim myString As String
Integer.TryParse(txtNumber.Text, intCount)
intNum = 0
Do While intNum < 12
intNum = intNum + 1
intAnswer = intNum * intCount
lblTable.Text = " " & intNum.ToString() & " * " & intCount.ToString() & " = " & intAnswer.ToString()
Loop
From the looks of it, every time the code loops it sets the label text to the current result, while overwriting the previous result.
If you want the label to display multiple lines of data, you can try something like this:
lblTable.Text &= " " & intNum.ToString() & " * " & intCount.ToString() & " = " & intAnswer.ToString() & Environment.NewLine
The "Environment.NewLine" at the end will add the newline between each result.
The "&" before the "=" is used to append to the end of the existing text. This is simlar to doing:
lblTable.Text = lblTable.Text & "..." & Environment.NewLine
Also, just a side note. If you want multiple lines in a label, you may need to set the AutoSize property to false and configure the desired size of the label properly.
On this line:
lblTable.Text = " " & intNum.ToString() & " * " & intCount.ToString() & " = " & intAnswer.ToString()
it is only storing the last result.
You will need to pre-pend the existing results to the new results.
Label1.Text &= " " & intNum.ToString() & " * " & intCount.ToString() & " = " & intAnswer.ToString() & Environment.NewLine
I added a & before the = so that the new results will be appended to the end of the existing contents of Label1 and a NewLine on the end to make it a little neater
Firstly, you are assigning the result of your loop to the same label, so you will only have one label.
If you want to create multiple labels you should be creating them as you go:
Dim top_pos as integer = 30 ' first label's Top
Dim left_pos as integer = 30 ' first label's Left
For intNum = 1 to 12 ' Im assuming you want the table from 1 to 12
intAnswer = intNum * intCount
Dim lbl As New Label
With lbl
.text = Cstr(intNum) & " * " & Cstr(intCount) & " = " & Cstr(intAnswer)
.location = New Point(left_pos,top_pos) 'set its position
... 'and so on
Me.Controls.Add(lbl)
End With
top_pos = top_pos + 30 ' moves the position for the next label.
Next

BC30420 'Sub Main' was not found error in a Windows Form app

I've created a Windows Form application. It is my understanding that you do not have to have a Sub Main() in a Windows Form app. However I'm getting this error when I build my project:
BC30420 'Sub Main' was not found in 'LoanCalculator.Module1'.
First of all I don't know why it's saying 'LoanCalculator.Module1'. Both my form and my class are named LoanCalculator.vb. When I started the project I started writing the code in the original module. Then I added a module, named it 'LoanCalculator' and moved what code I had written to that module and finished it there. I deleted the original module. Now it builds fine with the exception of this one error. Here's my code:
Imports System.Windows.Forms
Public Class LoanCalculator
Private Sub Calculate()
Dim str As String
Dim intLoanAmt As Integer
Dim intDown As Integer
Dim intFees As Integer
Dim intBalance As Integer
Dim dblIntsRate As Single
Dim intLoanTerm As Integer
Dim sngInterestPaid As Single
Dim intTermMonths As Integer
Dim dblMonthlyPmt As Integer
Dim intTotalPaid As Integer
Dim dblYon As Double
Dim dblXon As Double
Dim dblZon As Double
If Not CheckInput() Then
Return
End If
intLoanAmt = Convert.ToInt32(txtLoan.Text)
intFees = Convert.ToInt32(txtFees.Text)
intDown = Convert.ToInt32(txtDown.Text)
intBalance = Convert.ToInt32(intLoanAmt - intDown + intFees)
intLoanTerm = Convert.ToInt32(txtTerm.Text)
dblIntsRate = Convert.ToDouble(txtTerm.Text)
intTermMonths = intLoanTerm * 12
dblYon = dblIntsRate / 1200
dblXon = dblYon + 1
dblZon = Math.Pow(dblXon, intTermMonths) - 1
dblMonthlyPmt = (dblYon + (dblYon / dblZon)) * intBalance
intTotalPaid = dblMonthlyPmt * intTermMonths
sngInterestPaid = intTotalPaid - intBalance
str = "Loan balance =" & Space(11) & intBalance.ToString & vbCrLf
str = str & "Loan Term =" & Space(16) & intLoanTerm.ToString & " years" & vbCrLf
str = str & "Interest paid =" & Space(17) & intTotalPaid.ToString & vbCrLf
str = str & "Monthly payment =" & Space(5) & dblMonthlyPmt.ToString
lblResults.Text = str
End Sub
Private Function CheckInput() As Boolean
Dim strErr As String = ""
If txtLoan.Text.Length = 0 Then
strErr = "Enter loan amount" & vbCrLf
End If
If txtDown.Text.Length = 0 Then
strErr = strErr & "Enter down payment" & vbCrLf
End If
If txtInterest.Text.Length = 0 Then
strErr = strErr & "Enter interest rate" & vbCrLf
End If
If txtFees.Text.Length = 0 Then
strErr = strErr & "Enter fees" & vbCrLf
End If
If txtTerm.Text.Length = 0 Then
strErr = strErr & "Enter loan term" & vbCrLf
End If
If strErr.Length > 0 Then
MessageBox.Show(strErr)
Return False
Else
Return True
End If
End Function
End Class
How can I fix this?

Use AddDays function in vb.net

Need some help finishing up this program, everything works and runs like I want it but I need to display an inputbox that allows the user to enter in the date they want for their invoice stored in service_date and then this date will display in the listbox with all the other items that I have put in there. I know I need to use the AddDays function but I have no clue on how to do it, and researching online has just led me to 100 other things that aren't that.
So here is my code:
Dim Customer As String
Dim Phone As String
Dim Hours As Double
Dim Parts As Double
Dim due_date As String
Dim service_date As String
Private Sub cmdInputBox_Click()
Dim service_date = InputBox("Enter the date of service. (MM/DD?YYYY)")
MsgBox("That's your date, " & service_date.ToString)
Exit Sub
End Sub
Private Sub CustInfo_Click()
Customer = txtCustomer.Text
Phone = mtbPhone.Text
Double.TryParse(txtHours.Text, Hours)
Double.TryParse(txtParts.Text, Parts)
If Customer.Length < 0 Then
MessageBox.Show("Please enter customer information.")
End If
If Phone = "" Then
MessageBox.Show("Please enter phone number.")
End If
If Not Double.TryParse(txtHours.Text, Hours) Then
MessageBox.Show("Please enter labor hours.")
End If
If Not Double.TryParse(txtParts.Text, Parts) Then
MessageBox.Show("Please enter parts and supplies.")
End If
''Perform calculations
Dim Total_Cost As Double
Dim Labor_Cost As Double
Dim Parts_Cost As Double
Parts_Cost = (Parts * 0.5 * 2)
Labor_Cost = (Hours * 35)
Total_Cost = (Hours + Parts)
Customer = txtCustomer.Text
Phone = mtbPhone.Text
lstBill.Items.Clear()
lstBill.Items.Add("Customer: " & vbTab & Customer.ToUpper)
lstBill.Items.Add("Phone: " & vbTab & vbTab & Phone)
lstBill.Items.Add("Service Date: " & vbTab & due_date)
lstBill.Items.Add("Invoice Date: " & vbTab & service_date)
lstBill.Items.Add("Labor Cost: " & vbTab & FormatCurrency(Labor_Cost))
lstBill.Items.Add("Parts Cost: " & vbTab & FormatCurrency(Parts_Cost))
lstBill.Items.Add("Total Cost: " & vbTab & FormatCurrency(Total_Cost))
Exit Sub
End Sub
Private Sub btnBill_Click(sender As System.Object, e As System.EventArgs) Handles btnBill.Click
cmdInputBox_Click()
CustInfo_Click()
End Sub
Try this:
Dim strDate As String = InputBox("Enter date?", , "")
If strDate = "" Then Exit Sub
Dim dteDate As Date
Dim enUS As New System.Globalization.CultureInfo("en-US")
If Date.TryParseExact(strDate, "MM/dd/yyyy", enUS, Globalization.DateTimeStyles.AssumeLocal, dteDate) Then
MsgBox("Date is " & dteDate.ToString)
End If