Saving an array to file - vb.net

I been trying to save an array to file but I can only create the text file but no text shows up in actual file. The loop doesn't work the way I want to. I need to store the Cust array into text file.
Dim car(4) As Decimal
Dim Cust(4) As String
'Declare module-level constants.
Const PER_DAY_Integer As Integer = 15
Const PER_MILE_Decimal As Decimal = 0.12D
Private Sub CalcButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalcButton.Click
'Calculate the rental charges
Cust(0) = NameTextBox.Text
Cust(1) = AddressTextBox.Text
Cust(2) = CityTextBox.Text
Cust(3) = ZipTextBox.Text
Cust(4) = StateTextBox.Text
Try
car(0) = Decimal.Parse(BeginTextBox.Text)
Try
car(1) = Decimal.Parse(EndTextBox.Text)
Try
car(2) = Integer.Parse(DaysTextBox.Text)
'Calculate the number of miles driven and the charges
car(3) = car(1) - car(0)
car(4) = (car(3) * PER_MILE_Decimal + car(2) * PER_DAY_Integer)
'Display the results
TotalTextBox.Text = car(4).ToString("C")
MilesTextBox.Text = car(3).ToString("N1")
Catch ex As Exception
MessageBox.Show("Input Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
DaysTextBox.Focus()
End Try
Catch ex As Exception
MessageBox.Show("Input Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
EndTextBox.Focus()
End Try
Catch ex As Exception
MessageBox.Show("Input Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
BeginTextBox.Focus()
End Try
End Sub
Private Sub ClearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearButton.Click
'Clear the form
AddressTextBox.Clear()
CityTextBox.Clear()
StateTextBox.Clear()
ZipTextBox.Clear()
BeginTextBox.Clear()
EndTextBox.Clear()
DaysTextBox.Clear()
TotalTextBox.Clear()
MilesTextBox.Clear()
With NameTextBox
.Clear()
.Focus()
End With
End Sub
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
'End the program
Me.Close()
End Sub
Private Sub PrintButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintButton.Click
'Print the form
PrintForm1.PrintAction = Printing.PrintAction.PrintToPreview
PrintForm1.Print()
End Sub
Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
End Sub
Private Sub WriteBtn_Click(sender As Object, e As EventArgs) Handles WriteBtn.Click
Dim outFile As IO.StreamWriter
Dim int As Integer = 0
Dim count As Integer = 0
outFile = IO.File.CreateText("Cust.txt")
Do While int < count
outFile.WriteLine(Cust(1)(int))
int += 1
Loop
outFile.Close()
End Sub
End Class

You were asked where it failed when you debug and you obviously haven't even bothered to debug or you'd have seen the issue. Look at this from your code:
Dim int As Integer = 0
Dim count As Integer = 0
outFile = IO.File.CreateText("Cust.txt")
Do While int < count
outFile.WriteLine(Cust(1)(int))
int += 1
Loop
Is int ever going to be less than count?
You can replace the entire contents of that last event handler with one line:
IO.File.WriteAllLines("Cust.txt", Cust)
Of course, you should not be using file names alone but rather a file path, but that's another issue.

Related

Passing Values from (DataGridView1_Click) in a Form to another sub in another form

I want to pass value from (DataGridView1_Click) to another sub which is in another form
How To Achieve that?
Is there any way to do that, Please help me
Public Class SearchCustomers
Private Sub SearchCustomers_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtCustomerSearchBox.Text = ""
CBCustomerSearch.SelectedIndex = -1
txtCustomerSearchBox_TextChanged(Nothing, Nothing)
End Sub
This the click Event
' Private Sub DataGridView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.Click
'FrmCustomers mycustomers = New FrmCustomers()
' mycustomers.show_data(DataGridView1.CurrentRow.Cells(1).Value.ToString)
' End Sub
Private Sub DataGridView1_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
For I = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(I).Cells(0).Value = "Go"
Dim row As DataGridViewRow = DataGridView1.Rows(I)
row.Height = 25
Next
End Sub
Private Sub DataGridView1_CellContentClick( ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub DataGridView1_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.Click
Dim oForm As New FrmCustomers()
Dim CustomerCode As String
CustomerCode = (DataGridView1.CurrentRow.Cells(1).Value.ToString)
oForm.show_data(CustomerCode)
MsgBox(DataGridView1.CurrentRow.Cells(1).Value.ToString, MsgBoxStyle.Exclamation, "Warning Message")
End Sub
End Class
this is the sub method in form 2
I want from this method to show data from DB to TextBox as seen in the code below
Sub show_data(CustomerCod)
OpenFileDialog1.FileName = ""
Dim sqls = "SELECT * FROM Customers WHERE CustomerCode=N'" & (CustomerCod) & "'"
Dim adp As New SqlClient.SqlDataAdapter(sqls, SQLconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
MsgBox("no record found", MsgBoxStyle.Exclamation, "warning message")
Else
Dim dr = dt.Rows(0)
On Error Resume Next
CustomerCode.Text = dr!CustomerCode
CustomerName.Text = dr!CustomerName
Address.Text = dr!Address
Country.Text = dr!Country
City.Text = dr!City
Fax.Text = dr!Fax
Mobile.Text = dr!Mobile
Email.Text = dr!Email
Facebook.Text = dr!Facebook
Note.Text = dr!Note
'====================== Image Reincyrpation
If IsDBNull(dr!Cust_image) = False Then
Dim imgByteArray() As Byte
imgByteArray = CType(dr!Cust_image, Byte())
Dim stream As New MemoryStream(imgByteArray)
Dim bmp As New Bitmap(stream)
Cust_image.Image = Image.FromStream(stream)
stream.Close()
Label16.Visible = False
'================================================
End If
BtnEdit.Enabled = False
BtnDelete.Enabled = False
BtnSave.BackColor = Color.Red
CustomerName.Focus()
End If
End Sub
You can do like this (just to Call):
Private Sub DataGridView1_Click(sender As Object, e As EventArgs) Handles DataGridView1.Click
FrmCustomers.Show()
FrmCustomers.Hide()
FrmCustomers.show_data(CustomerCod)
FrmCustomers.Dispose()
End Sub

calculation error vb.net textbox

I am working with inventory system, Transaction form I had mainly 2 text box, first 1 is avaqty its from database available qty, other textbox is avqty from user adding qty.
When user add qty avaqty textbox automatically change to
(avaqty) -(avqty) but as an example 10-10 result come in -1
My code is:
Public Class transaction
Dim objcon As New connectionclass
Dim qty As String
Public Function getqty() As String
If itemid.Text = "" Then
Else
Try
objcon.myconnection.Open()
Dim getqty1 As New OleDbCommand("select balance from avaqty where item_id=" & itemid.Text & "", objcon.myconnection)
Dim reader As OleDbDataReader = getqty1.ExecuteReader
While reader.Read
qty = reader("balance")
End While
objcon.myconnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Return qty
End Function
Private Sub itemid_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles itemid.KeyPress
If Asc(e.KeyChar) = 13 Then
objcon.myconnection.Open()
Try
Dim getdata As New OleDbCommand("select*from itemtbl where item_id=" & itemid.Text & "", objcon.myconnection)
Dim reader As OleDbDataReader = getdata.ExecuteReader
While reader.Read
itemdesc.Text = reader("item_des").ToString
yom.Text = reader("unit_of_mesure").ToString
cost.Text = reader("item_cost").ToString
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
objcon.myconnection.Close()
End If
If getqty() = 0 Then
avaqty.Text = 0
Else
avaqty.Text = getqty()
End If
End Sub
Private Sub initem_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles initem.CheckedChanged
dataview.DataSource = GETDATA()
End Sub
Private Sub outitem_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles outitem.CheckedChanged
dataview.DataSource = GETDATA2()
End Sub
Private Sub avqty_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles avqty.TextChanged
Try
If avqty.Text = "" Then
avaqty.Text = getqty()
Else
avaqty.Text = CDbl(avaqty.Text - avqty.Text)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub avaqty_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles avaqty.TextChanged
If avaqty.Text < 0 Then
MsgBox("not inough qty")
avqty.Clear()
End If
End Sub
End Class

Multiple Definition with Identical Signatures

Dim WithEvents client As New WebClient
Private Sub DirectX9ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DirectX9ToolStripMenuItem.Click
Try
client.DownloadFileAsync(New Uri("http://download1588.mediafire.com/y9phz64wph4g/aqlp1m71mvuwo74/Direct+X+11+Update.rar"), "C:\Documents and Settings\All Users\Documents\Direct X 11 Update.RAR")
Catch ex As Exception
MsgBox("File already exists or is corrupted!")
End Try
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles client.DownloadFileCompleted
MsgBox("Direct X 9 has been successfully downloaded!", MsgBoxStyle.Information)
Label48.Visible = False
Label49.Visible = False
ProgressBar3.Visible = False
Label48.Text = "0 &"
Label49.Text = "0 / 0"
ProgressBar3.Value = 0
End Sub
Private Sub client_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles client.DownloadProgressChanged
Label48.Visible = True
Label49.Visible = True
ProgressBar3.Visible = True
Label48.Text = ProgressBar3.Value & "%"
Label49.Text = e.BytesReceived & " / " & e.TotalBytesToReceive
ProgressBar3.Value = e.ProgressPercentage
End Sub
Private Sub GeForceExperienceV2000ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GeForceExperienceV2000ToolStripMenuItem.Click
Try
client.DownloadFileAsync(New Uri("http://download903.mediafire.com/w91mlqdf6clg/a540a35f5ddcpbn/GeForce_Experience_v2.2.2.0.exe"), "C:\Documents and Settings\All Users\Documents\GeForce_Experience_v2.2.2.0.exe")
Catch ex As Exception
MsgBox("File already exists or is corrupted!")
End Try
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles client.DownloadFileCompleted
MsgBox("GeForce_Experience_v2.2.2.0 has been successfully downloaded!", MsgBoxStyle.Information)
Label48.Visible = False
Label49.Visible = False
ProgressBar3.Visible = False
Label48.Text = "0 &"
Label49.Text = "0 / 0"
ProgressBar3.Value = 0
End Sub
End Class
You got your answer in comments but just going to explain to make sure you understand what you can and can't do.
When you create a method you name it so that when you call it your program knows which one it is you want to call. When you name 2 methods the same way it does not know which one to use when it is called.
The only way to have 2 methods with the same name is if they have a different "signature" that means it can't be 100% identical. Different parameters will make your method's signature different even if they are called the same

Why isn't my vb.net code saving a row to my Access database? (Error)

I'm trying to add a 'coupling' to my database with the following code. It give me the error "Update requires a valid InsertCommand when passed DataRow collection with new rows."
Private Sub AddCoupling_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CouplingsTableAdapter.Fill(TestDatabaseDataSet.Couplings)
End Sub
Private Sub ButtonCancel_Click(sender As Object, e As EventArgs) Handles ButtonClose.Click
Close()
End Sub
Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
Dim newCoup As DataRow = TestDatabaseDataSet.Tables("Couplings").NewRow
newCoup.Item("Type") = ComboBoxType.Text
newCoup.Item("Part Number") = TextPartNumber.Text
newCoup.Item("Description") = TextDescription.Text
newCoup.Item("Rubber Type") = ComboBoxRubberType.Text
newCoup.Item("TKN") = Integer.Parse(TextTKN.Text)
newCoup.Item("TKmax") = Integer.Parse(TextTKmax.Text)
newCoup.Item("TKW") = Integer.Parse(TextTKW.Text)
newCoup.Item("Ambient Temp") = Integer.Parse(TextTemp.Text)
newCoup.Item("PKW") = Integer.Parse(TextPKW.Text)
newCoup.Item("Max Speed") = Integer.Parse(TextSpeed.Text)
Try
TestDatabaseDataSet.Tables("Couplings").Rows.Add(newCoup)
CouplingsTableAdapter.Adapter.Update(TestDatabaseDataSet) ' ERROR HERE '
MessageBox.Show("Saved!")
Close()
Catch ex As Exception
MessageBox.Show("Failed to save to database. E:" & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

Converting multiple Images to pdf using pdfsharp

I am trying to convert multiple images to pdf using pdfsharp library.
I am able to convert single image and it works pretty well.
And while converting bulk images to single pdf I am facing problem that it takes all the images and converts them but after conversion If I check it shows me only the last image as it is not appending to the existing image and it overwrites the previous image.
So how do I rectify this?
Any help will be appreciated as I am first time working with pdf library and point me out If I am doing any mistake.And I will be gald to know more about this and I don't feel though If you pointed me out the mistake I have done.
Here is my code:
Private Sub btnAddFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddFolder.Click
If Me.FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim f As New DirectoryInfo(Me.FolderBrowserDialog1.SelectedPath)
Dim fso As New System.Object
For Each file As FileInfo In f.GetFiles
Select Case file.Extension.ToLower
Case ".jpg", ".bmp", ".gif", ".png"
Me.ThumbControl1.BackgroundImage = Nothing
Me.CheckedListBox1.Items.Add(file.FullName, CheckState.Checked)
Me.ThumbControl1.AddThumbnail(file.FullName)
Me.ThumbControl1.BackgroundImage = Nothing
Me.CheckedListBox1.SelectedIndex = 0
End Select
Next
End If
End Sub
Background worker:
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bw.DoWork
For pix As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Try
Dim source As String = CheckedListBox1.Items(pix).ToString()
Dim destinaton As String = (TryCast(e.Argument, String()))(1)
Dim doc As New PdfDocument()
doc.Pages.Add(New PdfPage())
Dim xgr As XGraphics = XGraphics.FromPdfPage(doc.Pages(0))
Dim img As XImage = XImage.FromFile(source)
xgr.DrawImage(img, 0, 0)
doc.Save(destinaton)
doc.Close()
success = True
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next
End Sub
Convert button:
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConvert.Click
bw.RunWorkerAsync(New String(1) {srcFile, destFile})
End sub
Saving Pdf:
Private Sub btnSelectDest_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelectDest.Click
sfdDestFile.Filter = "PDF Files(*.pdf)|*.pdf"
If sfdDestFile.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
Return
End If
destFile = sfdDestFile.FileName
End Sub
The problem is that you are creating a new PDF document on each pass through the loop. You need to move this outside the loop. Also, you are referencing page 0, not page pix. Here is how I would fix it:
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bw.DoWork
Dim doc As New PdfDocument()
For pix As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Try
Dim source As String = CheckedListBox1.Items(pix).ToString()
Dim oPage As New PDFPage()
doc.Pages.Add(oPage)
Dim xgr As XGraphics = XGraphics.FromPdfPage(oPage)
Dim img As XImage = XImage.FromFile(source)
xgr.DrawImage(img, 0, 0)
success = True
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next
Dim destinaton As String = (TryCast(e.Argument, String()))(1)
doc.Save(destinaton)
doc.Close()
End Sub