I need to understand if there is a possibility, within VB.NET, to be able to read the columns of an Excel file and write them out to a CSV file in a different order.
In practice, the Excel file we are sent has 6 columns: "amount", "branch", stock "," proposal "," quantity "," type ". The company management system accepts the text file with the columns in a different order: "branch", "stock", "amount", "quantity", "type", "proposal". This creates a problem for me because when I go to convert it my ERP fails to recognize that the column is in a different position.
I arrive at the concrete question, I would like to have the possibility to read the columns and make it possible through a script to be able to position them according to the position I decide.
I tried this code for import and convert to txt, but I need another script:
Imports System.IO
Imports ExcelDataReader
Imports System.Text
Public Class Form1
Dim tables As DataTableCollection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "(*.xls)|*.xls|(*.xls)|*.xlsx"}
If ofd.ShowDialog() = DialogResult.OK Then
txtFileName.Text = ofd.FileName
Using Stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(Stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
tables = result.Tables
cboSheet.Items.Clear()
For Each table As DataTable In tables
cboSheet.Items.Add(table.TableName)
Next
End Using
End Using
End If
End Using
End Sub
Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged
Dim dt As DataTable = tables(cboSheet.SelectedItem.ToString())
dgProposte.DataSource = dt
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim writer As TextWriter = New StreamWriter("C:\Users\antonio\Desktop\Prova.txt")
For i As Integer = 0 To dgProposte.Rows.Count - 2 Step +1
For j As Integer = 0 To dgProposte.Columns.Count - 1 Step +1
writer.Write(vbTab & dgProposte.Rows(i).Cells(j).Value.ToString() & vbTab & "")
Next
writer.WriteLine("")
Next
writer.Close()
MessageBox.Show("Dati Esportati")
End Sub
The tables that you get from importing the Excel sheet(s) have their column names set, and you can index the column by its name.
So, and with a little adjustment to factor out some methods:
Imports System.IO
Imports ExcelDataReader
Public Class Form1
Dim tables As DataTableCollection
Private Sub WriteToCsv(tableName As String, filename As String)
Dim columnWriteOrder = {"branch", "stock", "amount", "quantity", "type", "proposal"}
Using writer As TextWriter = New StreamWriter(filename)
Dim tbl = tables(tableName)
For i As Integer = 0 To dgProposte.Rows.Count - 2
Dim vals As New List(Of String)
For j As Integer = 0 To columnWriteOrder.Length - 1
Dim val = tbl.Rows(i).Item(columnWriteOrder(j)).ToString()
vals.Add(val)
Next
writer.WriteLine(String.Join(vbTab, vals))
Next
End Using
End Sub
Private Sub PopulateSheetNames()
cboSheet.Items.Clear()
For Each table As DataTable In tables
cboSheet.Items.Add(table.TableName)
Next
End Sub
Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged
If cboSheet.SelectedIndex >= 0 Then
Dim tableName = cboSheet.SelectedItem.ToString()
Dim dt As DataTable = tables(tableName)
dgProposte.DataSource = dt
End If
End Sub
Private Sub bnLoad_Click(sender As Object, e As EventArgs) Handles bnLoad.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls", .InitialDirectory = "C:\temp"}
If ofd.ShowDialog() <> DialogResult.OK Then
Exit Sub
End If
txtFileName.Text = ofd.FileName
Using Stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(Stream)
Dim edsc = New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}}
Dim result As DataSet = reader.AsDataSet(edsc)
tables = result.Tables
End Using
End Using
PopulateSheetNames()
End Using
End Sub
Private Sub bnSaveAsCsv_Click(sender As Object, e As EventArgs) Handles bnSaveAsCsv.Click
If cboSheet.SelectedIndex < 0 Then
MessageBox.Show("Please select a sheet name.", "No sheet name selected", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Sub
End If
Dim sheetName = cboSheet.SelectedItem.ToString()
If Not String.IsNullOrEmpty(sheetName) Then
WriteToCsv(sheetName, "C:\temp\Prova.csv")
MessageBox.Show("Dati Esportati.", "Dati Esportati", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
I changed the names of the buttons because "Button1" and "Button2" are not descriptive.
(I set the .InitialDirectory of the OpenFileDialog because it was convenient for me.)
Why you don't map a DTO of your data table?
Public Class MioDto
Property campoUno As String
Property campoDue As String
'...ecc
End Class
and then you can fill a dto in a cicle or so...
Dim a As New MioDto() With {.campoUno="...", campoDue="..."}
or if you want you can use
https://github.com/AutoMapper/AutoMapper
When you have a Dto class filled you can use it for generate your txt with youor preferred order.
Related
I am exporting multiple DataTables to an Excel-file using ExcelLiabrary. The problem is that date column in all datatables, are being exported as number. DataTables are filled with data retrieved from Sql Server where the column type is date. Datagrids are also showing it correctly but in the excel it become numbers.
Here is the code to populate DataTable
Dim command = New SqlCommand("getdeta", sqlConn)
command.CommandType =
CommandType.StoredProcedure
Dim adapter = New SqlDataAdapter(command)
dt1 = New DataTable()
adapter.Fill(dt1)
dgv1.DataSource = dt1
and here is to Export data to Excel
Dim fileName = ExportAllDialog.FileName
datasetForExport.Tables.Add(dt1)
datasetForExport.Tables.Add(dt2)
ExcelLibrary.DataSetHelper.CreateWorkbook(fileName, datasetForExport)
So here is some code for the Microsoft.Office.Interop.Excel approach:
Option Strict On
Option Explicit On
Imports System.IO
Imports System.Runtime.InteropServices
Imports Excel = Microsoft.Office.Interop.Excel
Public Class ExcelBook
Private EXL As Excel.Application
Private Book As Excel.Workbook
Private Sheet As Excel.Worksheet
Private MyFileName As String
Protected Overrides Sub Finalize()
' Save and close the currently loaded Excel file
Close(True)
' Delete the local reference to the app BEFORE destroy
EXL = Nothing
MyBase.Finalize()
End Sub
Private Sub OpenApplication()
If EXL IsNot Nothing Then Return
EXL = New Excel.Application
EXL.Visible = False
EXL.DisplayAlerts = False
End Sub
Public Sub Open(Filename As String)
Open(Filename, 1)
End Sub
Public Sub Open(Filename As String, SheetIndex As Object)
OpenApplication()
' If another Excel file is open, close it
Close(True)
If File.Exists(Filename) Then
Book = EXL.Workbooks.Open(Filename)
Else
Book = EXL.Workbooks.Add()
End If
' Turns off warning messages when saving older files
Book.CheckCompatibility = False
UseSheet(SheetIndex)
MyFileName = Filename
End Sub
Public Sub Close(Save As Boolean)
If Book Is Nothing Then Return
If File.Exists(MyFileName) Then
Book.Close(Save)
Else
If Save Then Book.SaveAs(MyFileName)
Book.Close()
End If
Sheet = Nothing
Book = Nothing
MyFileName = Nothing
End Sub
Public Function UseSheet(Index As Object) As Boolean
If Book Is Nothing Then Return False
Try
Sheet = DirectCast(Book.Sheets(Index), Excel.Worksheet)
Sheet.Activate()
Return True
Catch Ex As COMException
Return False
End Try
End Function
Public Sub AddSheet(NewName As String)
AddSheet(NewName, Nothing)
End Sub
Public Sub AddSheet(NewName As String, Before As Object)
If Book Is Nothing Then Return
If SheetExists(NewName) Then Return
If Before Is Nothing OrElse Not SheetExists(Before) Then
Sheet = CType(Book.Sheets.Add(After:=Book.Sheets(Book.Sheets.Count)), Excel.Worksheet)
Else
Sheet = CType(Book.Sheets.Add(Before:=Book.Sheets(Before)), Excel.Worksheet)
End If
Sheet.Activate()
Sheet.Name = NewName
End Sub
Function SheetExists(Index As Object) As Boolean
If Book Is Nothing Then Return False
Dim LocalSheet As Excel.Worksheet
Try
LocalSheet = DirectCast(Book.Sheets(Index), Excel.Worksheet)
Catch Ex As COMException
LocalSheet = Nothing
End Try
Return LocalSheet IsNot Nothing
End Function
Public Sub RenameSheet(NewName As String)
If Sheet Is Nothing Then Return
If Not String.IsNullOrEmpty(NewName) Then Sheet.Name = NewName
End Sub
Public Sub FormatColumns(Columns As String, NewFormat As String)
If Sheet Is Nothing Then Return
Dim Rng = DirectCast(Sheet.Columns(Columns), Excel.Range)
Rng.NumberFormat = NewFormat
End Sub
Public Sub ImportTable(Table As DataTable)
If Sheet Is Nothing Then Return
If Table Is Nothing Then Return
If Table.Columns.Count = 0 Then Return
Dim Matrix(Table.Rows.Count, Table.Columns.Count) As Object
Dim Col As Integer
' Copy the datatable to an array
For Row As Integer = 0 To Table.Rows.Count - 1
For Col = 0 To Table.Columns.Count - 1
Matrix(Row, Col) = Table.Rows(Row).Item(Col)
Next
Next
' Add the column headers starting in A1
Col = 0
For Each Column As DataColumn In Table.Columns
Sheet.Cells(1, Col + 1) = Column.ColumnName
Col += 1
Next
' Add the data starting in cell A2
If Table.Rows.Count > 0 Then
Sheet.Range(Sheet.Cells(2, 1), Sheet.Cells(Table.Rows.Count + 1, Table.Columns.Count)).Value = Matrix
End If
End Sub
End Class
Then you could use this function to export your DataSet:
Private Sub ExportDataSet(DS As DataSet, Filename As String)
Dim DT As DataTable
Dim First As Boolean = True
With New ExcelBook
.Open(Filename)
For Each DT In DS.Tables
If First Then
.RenameSheet(DT.TableName)
First = False
Else
.AddSheet(DT.TableName)
End If
.ImportTable(DT)
Next
.UseSheet(1)
.Close(True)
End With
End Sub
Help me convert list view entries to excel then pdf. Or simply help me convert listview entries to PDF. l am using visual basic 2012. This is the code that l have:
Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
'Export the listview to an Excel spreadsheet
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.pdf)|*.pdf"
SaveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
'create objects to interface to Excel
Dim xls As New Excel.Application
Dim book As Excel.Workbook
Dim sheet As Excel.Worksheet
'create a workbook and get reference to first worksheet
xls.Workbooks.Add()
book = xls.ActiveWorkbook
sheet = book.ActiveSheet
'step through rows and columns and copy data to worksheet
Dim row As Integer = 1
Dim col As Integer = 1
For Each item As ListViewItem In CustomerView.Items
' lblID.Text = SalesView.SelectedItems(0).Text
For i As Integer = 0 To item.SubItems.Count - 1
sheet.Cells(row, col) = item.SubItems(i).Text
col = col + 1
Next
row += 1
col = 1
Next
'save the workbook and clean up
book.SaveAs(SaveFileDialog1.FileName)
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(book)
releaseObject(xls)
End Sub
Private Sub releaseObject(ByVal obj As Object)
'Release an automation object
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
I have a dialog form here where a user can upload a file from Excel and import and display to the datagrid view. However, my problem is when the user closes the application or form, the datagridview was empty and reset.
My question is how can I retrieve its data and display it, every time the user will open the form. Is it possible if the data was not saved in the database and will only based on the uploaded or imported Excel file? And if the user has uploaded a new Excel, I want to replace the existing rows or data in the datagridview.
I really hope you would help.
Below you can find my code:
Imports System.Data
Public Class frmSupplier
Private Sub btn_upload_supplier_Click(sender As Object, e As EventArgs) Handles btn_upload_supplier.Click
Try
If btn_upload_supplier.Text = "New" Then
Dim Openfile As New OpenFileDialog
Openfile.ShowDialog()
txtpath_supplier.Text = Openfile.FileName
Label1.Text = txtpath_supplier.Text
If txtpath_supplier.Text = Nothing Then
Else
btn_upload_supplier.Text = "Upload"
End If
ElseIf btn_upload_supplier.Text = "Upload" Then
Dim dtItemlist As New DataTable
Dim obj As New Basegeneral
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + txtpath_supplier.Text.ToString() + "; Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
dg_details.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MessageBox.Show(Me, ex.ToString, "Error:")
End Try
End If
Catch ex As Exception
MessageBox.Show(Me, ex.ToString, "Error:")
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim row As System.Data.DataRow = GridView1.GetDataRow(GridView1.FocusedRowHandle)
If row.Item(0).ToString = "" Then
MessageBox.Show("Please select supplier to remove", "KCC Retail System")
Return
End If
If DevExpress.XtraEditors.XtraMessageBox.Show("Are you sure you want to remove supplier '" & row.Item(0) & "'?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("Supplier " & row.Item(0) & " has been removed!", "KCC Retail System")
GridView1.DeleteRow(GridView1.FocusedRowHandle)
Else
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error :")
End Try
End Sub
Private Sub btn_clear_Click(sender As Object, e As EventArgs) Handles btn_clear.Click
btn_upload_supplier.Text = "New"
txtpath_supplier.Text = ""
End Sub
The form will be open when the user click the button and it will display as a dialog (ShowDialog).
To save and then re-hydrate the contents of a DataGridView you can use a binary formatter.
Imports System.IO
Import System.Runtime.Serialization.Formatters.Binary
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim FileName As String = "MyData.dat" 'Will save in bin directory
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
' 1. Create an instance of a Binary Formatter
Dim bf As New BinaryFormatter
' 2. Create a file stream passing in (the name of the file to create, mode: Create, access: Write, share: none)
Using fs As Stream = New FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None)
' 3. use the Serialize method of the Binary Formatter passing in the file stream(file name, create, write, no share) And the object
bf.Serialize(fs, dt)
End Using
End Sub
Private Sub btnFillFromFill_Click(sender As Object, e As EventArgs) Handles btnFillFromFill.Click
Dim FileName As String = "MyData.dat"
Dim dt As DataTable
' 1. Create an instance of Binary Formatter
Dim bf As New BinaryFormatter()
' 2. Get an instance of a FileStream for the OpenRead method of File passing in (the fileName)
Using fs As Stream = File.OpenRead(FileName)
' 3. cast back to original object, the Deserialize method of the Binary Formatter passing in the File Stream
dt = CType(bf.Deserialize(fs), DataTable)
End Using
DataGridView1.DataSource = dt
End Sub
enter image description hereenter image description hereI am just learning VB.NET and unfortunately I have been tasked with something I do not have a clue how to do.
I need to create a quick windows based application to export csv files into an XLSX file.
Yes, I know that other posts may have a similar topic however this one I believe is unique.
The CSV file will have 5 headers, `Line, Component, Picked, Placed and Missed. We have part numbers in column 2 that would be placed under Component. I am understanding from the powers that be, this file sums the total part numbers i.e. 0-5490045 and the line JUKI 3 and totals Picked, Placed and Missed parts. I have provided a sample rows below. First row is the csv formatted, the second is the output. I am not sure which loop would be best a FOR loop, WHILE loop etc. I am assuming I will need a loop of some sort to get through all the data in the csv file.
The only code I have opens the dialog box and allows for file selection and attempts to read into a datatable. I am attempting to get this working and then restructure some code.
Imports Spire.Xls
Imports System.Windows.Forms
Imports System.Data
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dialog As OpenFileDialog = New OpenFileDialog
dialog.Filter="CSV document(*.csv)|*.csv"
Dim result As DialogResult = dialog.ShowDialog
If(result=DialogResult.OK) Then
Dim csvFile As String = dialog.FileName
Dim workbook As Workbook = New Workbook
workbook.LoadFromFile(csvFile,",")
Dim worksheet As Worksheet = workbook.Worksheets(0)
Dim dt As DataTable=worksheet.ExportDataTable
Me.dataGridView1.DataSource=dt
End If
End Sub
End Class
JUKI 3 0-5490045 96 96 3
Line Component Picked Placed Missed
JUKI 3 0-5490045 99 96 3
I hate to make a suggestion and not show how it would work. Below is an example using a custom object called Machine to hold the data. This class is a bare minimum for an object and is only used as an example to get you started. It has some fields that will come in handy when looping thru the list to do your computations. It is also here you could add some custom functions/subs to help in some task that involves “Machine” objects. Also here you could add some compare functions which will enable you to sort among other things. After you put all this together you should end up with a list of valid Machine objects.
It is this list you could use to help you move on to the computing/removing duplicates part of your task. In the process of computing the data you could create a final list of Machine objects that you could use to export to excel with headers or display it to a DataGridView. Hope this helps.
Machine Class
Public Class Machine
Private name As String
Private partNumber As String
Private inventoryIn As Integer
Private inventoryOut As Integer
Private inventoryMissing As Integer
Public Sub New(inName As String, inPartNum As String, inInvIn As Integer, inInvOut As Integer, InInvMis As Integer)
name = inName
partNumber = inPartNum
inventoryIn = inInvIn
inventoryOut = inInvOut
inventoryMissing = InInvMis
End Sub
Property GetName As String
Get
Return name
End Get
Set(value As String)
name = value
End Set
End Property
Public Overrides Function ToString() As String
Return "Name: " + name + " #: " + partNumber + vbTab + " In:" + inventoryIn.ToString() + " Out:" + inventoryOut.ToString() + " Miss:" + inventoryMissing.ToString()
End Function
End Class
Now to your issue of reading the file
I did not use anything involving excel. Since you have a simple csv file we will use it. Also we will use the Machine class above. Using your open file dialog we get the name of the file to read. A variable partsList is created to hold the Machine objects created when reading the file. Then a for each loop goes through the list and displays the results in a text box on the form.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dialog As OpenFileDialog = New OpenFileDialog
dialog.Filter = "CSV document(*.csv)|*.csv"
Dim result As DialogResult = dialog.ShowDialog
If (result = DialogResult.OK) Then
Dim csvFile As String = dialog.FileName
Dim partsList As List(Of Machine) = ReadText(csvFile)
For Each curMac As Machine In partsList
TextBox1.AppendText(curMac.ToString() + Environment.NewLine)
Next
End If
End Sub
Function to read the csv file
Private Function ReadText(filePath As String) As List(Of Machine)
Dim fileReader As System.IO.StreamReader
Dim data As List(Of Machine) = New List(Of Machine)
fileReader = My.Computer.FileSystem.OpenTextFileReader(filePath)
Dim curline As String = ""
While (Not curline Is Nothing)
curline = fileReader.ReadLine()
'' need to check for valid data
'' if anything is invalid simply ignore it... i.e. your bad rows
'' keep in mind this will also ignore good rows that have a single piece of data bad
If (StringOK(curline)) Then
Dim newMac = GetMac(curline)
data.Add(newMac)
End If
End While
Return data
End Function
A couple of helper functions to validate the data
Private Function StringOK(inString As String) As Boolean
If (String.IsNullOrEmpty(inString)) Then
Return False
End If
Dim splitArray() As String = inString.Split(",")
Try
If ((String.IsNullOrEmpty(splitArray(0))) Or (String.IsNullOrEmpty(splitArray(1)))) Then
Return False
End If
Dim value As Integer
If ((Not Integer.TryParse(splitArray(2), value)) Or
(Not Integer.TryParse(splitArray(3), value)) Or
(Not Integer.TryParse(splitArray(4), value))) Then
Return False
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
Function GetMac(inString As String) As Machine
Dim splitArray() As String = inString.Split(",")
Dim value As Integer
Dim name As String = splitArray(0)
Dim number As String = splitArray(1)
Integer.TryParse(splitArray(2), value)
Dim invIn As Integer = value
Integer.TryParse(splitArray(3), value)
Dim invOut As Integer = value
Integer.TryParse(splitArray(4), value)
Dim invMis As Integer = value
Return New Machine(name, number, invIn, invOut, invMis)
End Function
If you are trying to accomplish how to import the data into a datatable below is a fast way of handling that. This will bring your whole csv into a datatable which you could then do logic on and create your xlsx file.
Friend Shared Function GetExcelFile(ByVal strFileName As String, ByVal strPath As String) As DataTable
Try
Dim dt As New DataTable
Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & strFileName, conn)
da.Fill(dt)
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
I have built a program that allows the user to search for a customer or add a new user with various information related to that customer. However when I run the program I get an error that says An unhandled exception of type 'System.OverflowException' occurred in Microsoft.VisualBasic.dll attached to the telephone number. I am not sure what I am doing wrong here.
My code:
Imports System.IO
Public Class Form1
Dim txtFile As StreamWriter ' object variable
Dim searchFile As StreamReader ' object variable
' structure declaration
Structure CustomerAccounts
Dim Records As StreamReader
Dim LastName As String
Dim FirstName As String
Dim CustomerNumber As String
Dim Address As String
Dim City As String
Dim State As String
Dim ZIPCode As Integer
Dim TelephoneNumber As Int64
Dim AccountBalance As Double
Dim DateOfLastPayment As String
End Structure
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub SaveCtrlSToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveCtrlSToolStripMenuItem.Click
Dim CustomerRecord As CustomerAccounts ' Structure Variable
' Assigning data to structure variable
CustomerRecord.LastName = txtLast.Text
CustomerRecord.FirstName = txtFirst.Text
CustomerRecord.CustomerNumber = txtNumber.Text
CustomerRecord.Address = txtAddress.Text
CustomerRecord.City = txtCity.Text
CustomerRecord.State = txtState.Text
CustomerRecord.ZIPCode = CInt(txtZIPCode.Text)
CustomerRecord.TelephoneNumber = CInt(txtTelephone.Text)
CustomerRecord.AccountBalance = CDbl(txtAccountBalance.Text)
While CustomerRecord.AccountBalance < 0
CustomerRecord.AccountBalance = CDbl(InputBox("Please enter a non-negative balance"))
End While
CustomerRecord.DateOfLastPayment = CDate(txtPayment.Text)
' Opening a file in append mode
txtFile = File.CreateText("Records.txt")
' Writing data to a file
txtFile.WriteLine(CustomerRecord.LastName)
txtFile.WriteLine(CustomerRecord.FirstName)
txtFile.WriteLine(CustomerRecord.CustomerNumber)
txtFile.WriteLine(CustomerRecord.Address)
txtFile.WriteLine(CustomerRecord.City)
txtFile.WriteLine(CustomerRecord.State)
txtFile.WriteLine(CustomerRecord.ZIPCode)
txtFile.WriteLine(CustomerRecord.TelephoneNumber)
txtFile.WriteLine(CustomerRecord.AccountBalance)
txtFile.WriteLine(CustomerRecord.DateOfLastPayment)
txtFile.Close() ' Close the data file after writing the data
clearFields()
End Sub
Private Sub ExitCtrlQToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitCtrlQToolStripMenuItem.Click
' Close the form
Me.Close()
End Sub
Private Sub SearchToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles SearchToolStripMenuItem1.Click
' Open a file in read mode
searchFile = File.OpenText("Records.Txt")
Dim lastName As String
Dim flag As Integer
flag = 0
' get the record name from user input
lastName = InputBox("Please enter the last name to search")
Dim CSearchRecord As CustomerAccounts
Try
While Not searchFile.EndOfStream
CSearchRecord.LastName = searchFile.ReadLine()
CSearchRecord.FirstName = searchFile.ReadLine()
CSearchRecord.CustomerNumber = searchFile.ReadLine()
CSearchRecord.Address = searchFile.ReadLine()
CSearchRecord.City = searchFile.ReadLine()
CSearchRecord.State = searchFile.ReadLine()
CSearchRecord.ZIPCode = searchFile.ReadLine()
CSearchRecord.TelephoneNumber = searchFile.ReadLine()
CSearchRecord.AccountBalance = searchFile.ReadLine()
CSearchRecord.DateOfLastPayment = searchFile.ReadLine()
' Compare current record with search record
If CSearchRecord.LastName.Equals(lastName) Then
flag = 1
Exit While
End If
End While
' If record found display txt fields
If flag.Equals(1) Then
txtLast.Text = CSearchRecord.LastName.ToString()
txtFirst.Text = CSearchRecord.FirstName.ToString()
txtNumber.Text = CSearchRecord.CustomerNumber.ToString()
txtAddress.Text = CSearchRecord.Address.ToString()
txtCity.Text = CSearchRecord.City.ToString()
txtState.Text = CSearchRecord.City.ToString()
txtZIPCode.Text = CSearchRecord.ZIPCode.ToString()
txtTelephone.Text = CSearchRecord.TelephoneNumber.ToString()
txtAccountBalance.Text = CSearchRecord.AccountBalance.ToString()
txtPayment.Text = CSearchRecord.DateOfLastPayment.ToString()
Else
' If record not found alert user
MessageBox.Show("Record Not Found")
clearFields()
End If
Catch ex As Exception
End Try
End Sub
Private Sub ReportToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ReportToolStripMenuItem1.Click
Dim report As String
report = "Report of Customer Accounts" + vbNewLine
' Open file in read mode
searchFile = File.OpenText("Record.txt")
Try
' Reading the file until end
While Not searchFile.EndOfStream
report += searchFile.ReadLine() + " "
report += searchFile.ReadLine() + " "
report += searchFile.ReadLine() + " "
report += searchFile.ReadLine() + " "
report += vbNewLine
End While
Catch ex As Exception
End Try
' Display file Content as report
MessageBox.Show(report)
End Sub
Private Sub clearFields()
txtAccountBalance.Clear()
txtAddress.Clear()
txtCity.Clear()
txtFirst.Clear()
txtLast.Clear()
txtNumber.Clear()
txtPayment.Clear()
txtState.Clear()
txtTelephone.Clear()
txtZIPCode.Clear()
End Sub
End Class
Any help offered would be greatly appreciated. I just need to know how to fix this.