closing mdi child form causes System.ObjectDisposedException - vb.net

i created a mdi database application. One child form has a datagridview. when clicking on a button on that form a new form opens with a pdfviewer(AxAcroPDF1) on it. This form shows a pdf document stored in the sql server database.
closing this form is done by Me.Close(). It closes it, but when i do it several times, opening that form and closing it, then at one point i get a
System.ObjectDisposedException which says Cannot access a disposed object and it isn't caught either in the try catch block.
It also says The application is in break mode. Your app has entered a break state, but there is no code to show because all threads where executing external code(typically system or framwork code)
Never experienced this kind of problem before.
Here is the code to launch the form with the pdf viewer
Private Sub btnShowDocument_Click(sender As Object, e As EventArgs) Handles btnShowDocument.Click
frmDocument = New frmShowDocumentatie
rowIndex = dgvData.CurrentRow.Index
FileName = dgvData.Item(6, rowIndex).Value
If FileName = "" Then
MessageBox.Show("Can't open documentation" & vbNewLine & "File doesn't exist", "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
frmDocument.Show()
End If
End Sub
And here's the form that opens up then
Imports System.Data.SqlClient
Public Class frmShowDocumentatie
'local variables to get passed the public shared values from
'curent selected row index and document name in datagridview
Private iRow As Integer
Private fName As String
Private Sub frmShowDocumentatie_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'sets the mdi parent
MdiParent = MDIParent1
'sets the text of the form to the filename of pdf bestand
Me.Text = "Document: " & getFilename()
'loads the pdf bestand, need the filepath which is provided by getfilepath function
AxAcroPDF1.src = GetFilePath()
'gets the values from the selected row index and corrsponding filename
iRow = frmDataView.rowIndex
fName = frmDataView.FileName
tsmiDocument.Text = "Document: " & getFilename()
End Sub
'function for getting the filename of selected pdf file in datagridview
Public Function getFilename() As String
fName = frmDataView.FileName
getFilename = fName
End Function
'gets the file path of selected pdf bestand
Function GetFilePath() As String
'Dim i As Integer = frmVerledenOverzicht.dgvData.CurrentRow.Index
'Dim filename As String = frmVerledenOverzicht.dgvData.Item(6, i).Value
Dim sFilePath As String
Dim buffer As Byte()
Using conn As New SqlConnection("Server=.\SQLEXPRESS;Initial Catalog=AndriesKamminga;Integrated Security=True;Pooling=False")
conn.Open()
Using cmd As New SqlCommand("Select Bestand From dbo.PaVerledenOverzicht WHERE Documentatie =" & "'" & getFilename() & "';", conn)
buffer = cmd.ExecuteScalar()
End Using
conn.Close()
End Using
sFilePath = System.IO.Path.GetTempFileName()
System.IO.File.Move(sFilePath, System.IO.Path.ChangeExtension(sFilePath, ".pdf"))
sFilePath = System.IO.Path.ChangeExtension(sFilePath, ".pdf")
System.IO.File.WriteAllBytes(sFilePath, buffer)
'returns the file path needed for AxAcroPDF1
GetFilePath = sFilePath
End Function
Private Sub tsmiSluiten_Click(sender As Object, e As EventArgs) Handles tsmiSluiten.Click
Try
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
anyone knows what's causing this exception and why is the program crashing instead of being caught in the try catch block
Am using visual studio community edition 2017

Related

Allowing multiple files to be processed through one module

I've created a program to modify security settings of a .pdf file.
This works fine for one file - but I want to allow editing multiple .pdf's with the touch of one button and am struggling to make it work.
I have pasted the code for my GUI below, "Modify_PDF" is the module that runs the pdf security modification code. Is it possible to run multiple files through this module from here?
Dim source_file As String = ""
''' Handles clicking of the 'Open file' button
Private Sub open_button_Click(sender As System.Object, e As System.EventArgs) Handles open_button.Click
Dim input As FileStream = Nothing
'Set filter to only allow compatible files
OpenFileDialog.Filter = "PDF documents (*.pdf)|*.pdf"
'Allow multiple files to be opened
OpenFileDialog.Multiselect = True
'open the file selection dialogue
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
input = OpenFileDialog.OpenFile()
Catch Ex As Exception
MsgBox("Error opening file: " & vbCrLf & Ex.Message)
Finally
'Check this again to ensure no exception on open.
If (input IsNot Nothing) Then
input.Close()
End If
End Try
If input IsNot Nothing Then
source_file = OpenFileDialog.FileName
If Modify_PDF.process_file(source_file, "") Then
PDF_name.Text = Path.GetFileName(OpenFileDialog.FileName)
input.Close()
modify_button.Enabled = Modify_PDF.process_file(source_file, "") 'Allow report to be created if processing succeeds
End If
End If
End If
End Sub
''' Handles clicking of the 'Modify PDF' button
Private Sub generate_button_Click(sender As System.Object, e As System.EventArgs) Handles modify_button.Click
Modify_PDF.modify_pdf(source_file, source_file, "")
End Sub
Try it like this:
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
For Each FileName as String in OpenFileDialog.FileNames
'Do something with the filename here
Next
Catch ...

VB Populating ComboBox with specific field from comma-delimited txt file

Need to populate NameComboBox from a comma-delimited txt file. Want user to be able to select just the name from NameComboBox dropdown and the rest of the textboxes to fill in.
Right now the entire record is populating the ComboBox.
Imports System.IO
Public Class LookupForm
Private Sub LookupForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Dim NameString As String
Try
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
NameString = ContactInfoStreamReader.ReadLine()
NameComboBox.Items.Add(NameString)
Loop
' Close the file.
ContactInfoStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("Create a new file?", "File Not Found",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If ResponseDialogResult = Windows.Forms.DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
****Update 11/2/15:
The names are appearing in the NamesComboBox as they should but when one is selected the info doesn't show in the other text boxes. Also as soon as form loads its already putting info in the other textboxes (from the 1st record in the array) before any name is selected from NamesComboBox.
Heres my streamwrite form
Imports System.IO
Public Class ContactInfoForm
' Declare module-level variable.
Private ContactInfoStreamWriter As StreamWriter
Private Sub SaveButton_Click(sender As System.Object, e As System.EventArgs) Handles SaveButton.Click
' Save the users contact information to the end of the file.
' Make sure name field and at least 1 number field is not empty.
If NameTextBox.Text <> "" And PhoneNumberTextBox.Text <> "" Or PagerNumberTextBox.Text <> "" Or
CellPhoneNumberTextBox.Text <> "" Or VoiceMailNumberTextBox.Text <> "" Then
If ContactInfoStreamWriter IsNot Nothing Then ' Check if the file is open
Dim info As String = ""
info = String.Format("{0},{1},{2},{3},{4},{5}", _
NameTextBox.Text, PhoneNumberTextBox.Text, PagerNumberTextBox.Text,
CellPhoneNumberTextBox.Text, VoiceMailNumberTextBox.Text, EmailAddressTextBox.Text)
ContactInfoStreamWriter.WriteLine(info)
With NameTextBox
.Clear()
.Focus()
End With
PhoneNumberTextBox.Clear()
PagerNumberTextBox.Clear()
CellPhoneNumberTextBox.Clear()
VoiceMailNumberTextBox.Clear()
EmailAddressTextBox.Clear()
Else ' File is not open
MessageBox.Show("You must open the file before you can save your contact information.", "File is Not Open",
MessageBoxButtons.OK, MessageBoxIcon.Information)
' Display the File Open dialog box.
OpenToolStripMenuItem_Click(sender, e)
End If
Else
MessageBox.Show("Please enter your name and at least 1 number where you can be reached.", "Data Entry Error",
MessageBoxButtons.OK)
NameTextBox.Focus()
End If
End Sub
Heres my Streamread section on the form to lookup in combo box.
Imports System.IO
Public Class LookupForm
Private Sub LookupForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Dim LineString As String
Dim FieldString As String()
Try
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("C:\Users\Cherokee\Documents\Cherokees Files\School Stuff\Visual Basic\Week 8 Data Files\pg465Ex11.5\pg465Ex11.5\pg465Ex11.5\bin\Debug\TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
LineString = ContactInfoStreamReader.ReadLine()
FieldString = LineString.Split(CChar(","))
LineString = FieldString(0) 'Take First Field
NameComboBox.Items.Add(LineString)
'Set Textboxes based on position in line.
PhoneNumberTextBox.Text = FieldString(1)
PagerNumberTextBox.Text = FieldString(2)
CellPhoneNumberTextBox.Text = FieldString(3)
VoiceMailNumberTextBox.Text = FieldString(4)
EmailAddressTextBox.Text = FieldString(5)
Loop
' Close the file.
ContactInfoStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("Create a new file?", "File Not Found",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If ResponseDialogResult = Windows.Forms.DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
You can Split the line read and take the column position you require as for example if first column is the name then your code becomes as below:
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
String lineRead = ContactInfoStreamReader.ReadLine()
Dim fields as String() = lineRead.Split(",")
NameString = fields(0) 'Take First Field
NameComboBox.Items.Add(NameString)
'Set Textboxes based on position in line.
'E.g. if Age is column 2 then
AgeTextBox.Text = fields(1)
Loop
' Close the file.
ContactInfoStreamReader.Close()

Calling a procedure from its non native form

Ok, so
frmResult populates a ListView with various calculations
frmMenu has an export button (see code below). Pressing this is supposed to export the data in the ListView to a txt file. Currently, this button does not work. It says, List View is undeclared - obviously because the code shown below is not 'seeing' data held in frmResult
Question – how do I call the procedures stored in frmResult so that frmMenu can 'see' it.
Public Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
'Request filename from user
Dim saveFile As String = InputBox("Enter a file name to save this message")
'Click Cancel to exit saving the work
If saveFile = "" Then Exit Sub
'
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
filePath = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'the filePath String contains the path you want to save the file to.
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
rtb.AppendText(
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
Next
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)
End Sub
Is this what you mean?
Public Sub Init()
'... (all the code)
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init()
End Sub
You can call Init() from every form load you want. Maybe you want to create a module and store there your methods.
By the way, you only use Function when your methods needs to return a value.
If your code uses elements of the form (or other objects not constant) you need to pass those to the method, like this:
Public Sub Init(myListView As ListView)
myListView.Items.Add("something")
'...
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init(ListView1)
End Sub
You can add as many parameters as you need. You have to learn the basics before going ant further.
This is a great piece of literature for those struggling with the basics like myself.
You can write code to access objects on a different form. However, you must fully identify the name of the object by preceding it with the object variable name.
Dim resultsForm As New frmResults
resultsForm.lblAverage.Text = sngAverage.ToString()
In these statements, for example, I have declared an object variable called resultsForm that is linked to the form frmResults. The second statement assigns the string value of sngAverage to the lblAverage label box on the frmResults form.
In my code, I needed to change the line that said:
For Each saveitem As ListViewItem In ListView1.Items
To this:
For Each saveitem As ListViewItem In Results.ListView1.Items
I also needed to make sure that the procedure on formResults was made Public not Private

upload multiple files to a local folder in vb.net

I am trying to create a function that will allow user to upload multiple files to a local folder.
currently i am able to upload just one file. i needed to upload more files in one go.
what i use for opening files/folder
a.Multiselect = True
If a.ShowDialog() = Windows.Forms.DialogResult.OK Then
removeatt.Show()
removeatt.Text = "Remove Attachment"
fpath.Text = a.FileName
address.Text = System.IO.Path.GetFileName(a.FileName)
Dim file As String
file = fpath.Text.ToString
Label7.Text = file
If fpath.Text = "-" Then
removeatt.Hide()
Else
removeatt.Show()
End If
End If
what i use for saving attachment
If fpath.Text = "-" Then
Else
My.Computer.FileSystem.CopyFile(fpath.Text = "-", dir2 + Upload.Label16.Text, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End If
any help is appreciated
thanks
It is not entirely clear to me where you handle the selected files, the first one is about removing attachments and the saving-part is not about uploading, it saves a file to the disk of the user as it seems.
Generally i'd recommend you to write a function that handles one file at a time so you can feed the function with the list of files to be copied in a for each-loop. The function is a bit "basic" to demonstrate what i mean.
Public Function CopyToDisk(ByVal DestinationPath As String, ByVal Sourcepath As String) As String
If Not System.IO.File.Exists(Sourcepath) Then
Return "Source missing" & Sourcepath
End If
Try
File.Copy(Sourcepath, DestinationPath)
Catch ex As Exception
Return ex.Message
End Try
Return "ok"
End Function
Well, have a look at the example from MSDN here, it has a filepicker and then it puts the objects in an array you can loop through and copy it where you want it to copy.
Here is the MSDN-original
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
InitializeOpenFileDialog()
End Sub
Private Sub Selectfilebutton_Click_1(sender As Object, e As EventArgs) Handles Selectfilebutton.Click
Dim dr As DialogResult = Me.OpenFileDialog1.ShowDialog()
If (dr = System.Windows.Forms.DialogResult.OK) Then
' Read the files
Dim file As String
For Each file In OpenFileDialog1.FileNames
'' you can loop through the array of objects and use a function to do the copying
' so for instance with my function it would be :
' copytodisk(Destination, file.filename)
' Create a PictureBox for each file, and add that file to the FlowLayoutPanel.
Try
Dim pb As New PictureBox()
Dim loadedImage As Image = Image.FromFile(file)
pb.Height = loadedImage.Height
pb.Width = loadedImage.Width
pb.Image = loadedImage
FlowLayoutPanel1.Controls.Add(pb)
Catch SecEx As SecurityException
' The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" & _
"Error message: " & SecEx.Message & "\n\n" & _
"Details (send to Support):\n\n" & SecEx.StackTrace)
Catch ex As Exception
' Could not load the image - probably permissions-related.
MessageBox.Show(("Cannot display the image: " & file.Substring(file.LastIndexOf("\"c)) & _
". You may not have permission to read the file, or " + "it may be corrupt." _
& ControlChars.Lf & ControlChars.Lf & "Reported error: " & ex.Message))
End Try
Next file
End If
End Sub
Public Sub InitializeOpenFileDialog()
' Set the file dialog to filter for graphics files.
Me.OpenFileDialog1.Filter = _
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + _
"All files (*.*)|*.*"
' Allow the user to select multiple images.
Me.OpenFileDialog1.Multiselect = True
Me.OpenFileDialog1.Title = "My Image Browser"
End Sub

Argument Exception - The path is not of a legal form (vb.net)

I'm currently having the most irritating error in a program i'm making and i would seriously appreciate any help or advice that could help me fix it. The part of the program that i'm having a problem with is a form that loads up a selected image into a picturebox and then saves it into an MS Access database upon the click of the 'save' button. When executing the "Browse_Click" event, it prompts you to search for an image location and loads it into a picturebox (pbImage). This bit works fine and successfully loads it into it picturebox. The problem i'm having is when i try to save the image to my access database, i get the following argument exception error "The path is not of a legal form".
As far as i know all my code is fully functional because it previously worked, however an hour or two ago this error suddenly started appearing.
The first section of code below is what is executed when i want to load the picture into the picture box. The section below that is the 'save' code.
Public Class Manage_Cottages
Dim imgName As String
Dim daImage As OleDbDataAdapter
Dim dsImage As DataSet
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Dim dlgImage As FileDialog = New OpenFileDialog()
dlgImage.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif"
If dlgImage.ShowDialog() = DialogResult.OK Then
imgName = dlgImage.FileName
Dim selectedFileName As String = dlgImage.FileName
txtPath.Text = selectedFileName
Dim newimg As New Bitmap(imgName)
pbImage.SizeMode = PictureBoxSizeMode.StretchImage
pbImage.Image = DirectCast(newimg, Image)
End If
dlgImage = Nothing
imgName = " "
End Sub'
Save code
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\Debug\CourseworkDatabase.mdb"
Dim CN As New OleDbConnection(cnString)
CN.Open()
If imgName <> "" Then
Dim fs As FileStream
fs = New FileStream(imgName, FileMode.Open, FileAccess.Read) <----- where the error occurs.
Dim picByte As Byte() = New Byte(fs.Length - 1) {}
fs.Read(picByte, 0, System.Convert.ToInt32(fs.Length))
fs.Close()
Dim strSQL As String
strSQL = "INSERT INTO Cottage_Details([Image]) values (" & " #Img)"
Dim imgParam As New OleDbParameter()
imgParam.OleDbType = OleDbType.Binary
imgParam.ParameterName = "Img"
imgParam.Value = picByte
Dim cmd As New OleDbCommand(strSQL, CN)
cmd.Parameters.Add(imgParam)
cmd.ExecuteNonQuery()
MessageBox.Show("Image successfully saved.")
cmd.Dispose()
CN.Close()
End If
End Sub
Also below is the first couple of lines of what's displayed in the immediate window (not sure whether it will be of any help to diagnose the problem)
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
System.Transactions Critical: 0 : http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/UnhandledUnhandled exceptionAlphaHolidayCottages.vshost.exeSystem.ArgumentException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089The path is not of a legal form. at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength)
Thanks for your time and help, would be over the moon if someone could help me resolve the issue.
Chris
You set imgName to " " at the end of btnBrowse_Click, so when you save the file under btnSave_Click you are trying to save it to the file name " ".
Try removing imgName = " " at the end of btnBrowse_Click, or assign imgName a proper file name before you save it.