Deletion of image from folder that is referenced to picture box - vb.net

sorry i have to rewrite this question as i did not get any update on my same question posted previously.
Below is the code where I'm inserting some data into Ms Access database in visual studio using vb. Net.
When i insert the data i also browse the image for that item and save into the folder that is located under project directory for universal access.
There is a datagridview which displays the data which was inserted to access databas alog with the image in picture box. Whenever the the datagrid view selection is change it display the picure into picture box.
I am having a trouble when i want to delete the data along with image located in project folder as it show the error that 'file used by another process, cant be deleted'
Since i have referenced that image to my picture box, it can not be deleted directly. So here I'm looking for a solution which can display the clone of image in picture box instead of real object.
Below is my code
Public Class frmMainCetegory
Private Sub frmMainCetegory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosDatabaseDataSet.tblItemMainCategory' table. You can move, or remove it, as needed.
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.CenterToParent()
Me.btnAddNew.Select()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
Try
Me.TblItemMainCategoryBindingSource.AddNew()
Me.txtMainCategory.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If Me.txtMainCategory.Text = "" Then
MsgBox("Please Enter Main Category Name!", vbInformation)
Exit Sub
End If
Me.imgMainCategoryImage.Image.Save(Application.StartupPath & "\Images\" & Me.txtMainCategory.Text & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Me.TblItemMainCategoryBindingSource.EndEdit()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.btnAddNew.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim MainCatName As String
MainCatName = Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value
If Me.TblItemMainCategoryDataGridView.Rows.Count - 1 > 0 Then
'check before delting, if this main category is used in sub category then It can not be deleted.
Dim I As Integer
I = frmSubCategories.TblItemSubCategoryTableAdapter.qryCountMainCategoryUnderSubCategory(MainCatName)
If I > 0 Then
MsgBox(MainCatName & " is used under Sub Category(s), Please Delete Sub Category(s) First!", vbOK)
Exit Sub
End If
End If
Me.TblItemMainCategoryBindingSource.RemoveCurrent()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
'Delete the Main Category Image if this exists
If System.IO.File.Exists(Application.StartupPath & "\Images\" & MainCatName & ".JPEG") Then
System.IO.File.Delete(Application.StartupPath & "\Images\" & MainCatName & ".JPEG")
MsgBox("Image Deleted Successfull")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Try
Me.OpenFileDialog1.Filter = "Bitmaps(*.JPG, *.PNG, *.JPEG, *.BMP, *.TIF, *.GIF, *.TIFF)|"
Me.OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim img As String = Me.OpenFileDialog1.FileName
Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(img)
Me.btnSave.Select()
Else
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub TblItemMainCategoryDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TblItemMainCategoryDataGridView.SelectionChanged
Try
Me.imgMainCategoryImage.Image = DirectCast(Image.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG").Clone(), Image)
' Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG")
Catch ex As Exception
Me.imgMainCategoryImage.Image = My.Resources.imgEmpty 'if image path not found then select empty image
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
frmTable.Show()
End Sub
End Class

Related

How to delete a file used by another Process

Public Class frmMainCetegory
Private Sub frmMainCetegory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PosDatabaseDataSet.tblItemMainCategory' table. You can move, or remove it, as needed.
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.CenterToParent()
Me.btnAddNew.Select()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
Try
Me.TblItemMainCategoryBindingSource.AddNew()
Me.txtMainCategory.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If Me.txtMainCategory.Text = "" Then
MsgBox("Please Enter Main Category Name!", vbInformation)
Exit Sub
End If
Me.imgMainCategoryImage.Image.Save(Application.StartupPath & "\Images\" & Me.txtMainCategory.Text & ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
Me.TblItemMainCategoryBindingSource.EndEdit()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.btnAddNew.Select()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim MainCatName As String
MainCatName = Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value
If Me.TblItemMainCategoryDataGridView.Rows.Count - 1 > 0 Then
'check before delting, if this main category is used in sub category then It can not be deleted.
Dim I As Integer
I = frmSubCategories.TblItemSubCategoryTableAdapter.qryCountMainCategoryUnderSubCategory(MainCatName)
If I > 0 Then
MsgBox(MainCatName & " is used under Sub Category(s), Please Delete Sub Category(s) First!", vbOK)
Exit Sub
End If
End If
Me.TblItemMainCategoryBindingSource.RemoveCurrent()
Me.TblItemMainCategoryTableAdapter.Update(Me.PosDatabaseDataSet.tblItemMainCategory)
Me.TblItemMainCategoryTableAdapter.Fill(Me.PosDatabaseDataSet.tblItemMainCategory)
'Delete the Main Category Image if this exists
If System.IO.File.Exists(Application.StartupPath & "\Images\" & MainCatName & ".JPEG") Then
System.IO.File.Delete(Application.StartupPath & "\Images\" & MainCatName & ".JPEG")
MsgBox("Image Deleted Successfull")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Try
Me.OpenFileDialog1.Filter = "Bitmaps(*.JPG, *.PNG, *.JPEG, *.BMP, *.TIF, *.GIF, *.TIFF)|"
Me.OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
Dim img As String = Me.OpenFileDialog1.FileName
Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(img)
Me.btnSave.Select()
Else
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub TblItemMainCategoryDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles TblItemMainCategoryDataGridView.SelectionChanged
Try
Me.imgMainCategoryImage.Image = DirectCast(Image.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG").Clone(), Image)
' Me.imgMainCategoryImage.Image = System.Drawing.Bitmap.FromFile(Application.StartupPath & "\Images\" & Me.TblItemMainCategoryDataGridView.CurrentRow.Cells("MainCategoryName").Value & ".JPEG")
Catch ex As Exception
Me.imgMainCategoryImage.Image = My.Resources.imgEmpty 'if image path not found then select empty image
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
End Class
Above code give me an error message:
image is used in another process, can't be deleted
when I delete the image file. The image is assigned to a PictureBox with selection event of the DataGridView. Since I have deleted the DataGridView row, as shown in the above code, it changes the image in the PictureBox.
Here I am unable to delete the image file related to the removed row.
Please guide and let me know if you need any further details.

Increasing memory usage while scrolling on listview items in vb.net

In a WinForm i have two listview(lvwTemplateCategory) one is listing folders at given directory and if you select folder, other listview(lvwTemplates) shows the files under this directory. I have also one picturebox(picTemplateImage) to show preview screenshot of that file.
While i'm scrolling on that form for 2-3 folders and 9-10 files it's memory usage goes from 62 MB to 120 MB.
I don't know how to manage the memory source also i tried to implement IDisposable but not know where to implement.
P.S. I'm using VS 2017 and calling that WinForm with .Show() method.
Also if you see non-logic codes please let me know.
Option Explicit On
Option Strict On
Imports System.IO
Public Class frmCreateNewModel
Implements IDisposable
Private Sub LoadForm(sender As Object, e As EventArgs) Handles MyBase.Load
Call AddRootDatabase()
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
End Sub
Private Sub ViewLargeIcons(sender As Object, e As EventArgs) Handles cmdViewLargeIcons.Click
lvwTemplateCategory.View = View.LargeIcon
End Sub
Private Sub ViewListIcons(sender As Object, e As EventArgs) Handles cmdViewList.Click
lvwTemplateCategory.View = View.List
End Sub
Private Sub AddRootDatabase()
Try
Dim DirDB As String = My.Settings.str_db__path_tpl
Dim DirInfoDB As New DirectoryInfo(DirDB)
For Each TplDirDB As DirectoryInfo In DirInfoDB.GetDirectories
If Not (TplDirDB.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
cboTemplateDatabase.Items.Add(TplDirDB.Name)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectRootDatabase(sender As Object, e As EventArgs) Handles cboTemplateDatabase.SelectedIndexChanged
Try
lvwTemplateCategory.Items.Clear()
lvwTemplates.Items.Clear()
Dim DirTempRootDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString
Dim DirTempDbInfo As New DirectoryInfo(DirTempRootDir)
Dim lstIcon As Integer
For Each TplCatDir As DirectoryInfo In DirTempDbInfo.GetDirectories
If Not (TplCatDir.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If imgIcons.Images.ContainsKey(TplCatDir.Name) = True Then
lstIcon = imgIcons.Images.IndexOfKey(TplCatDir.Name)
Else
lstIcon = imgIcons.Images.IndexOfKey("default")
End If
lvwTemplateCategory.Items.Add(TplCatDir.Name, lstIcon)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplateCategory(sender As Object, e As EventArgs) Handles lvwTemplateCategory.SelectedIndexChanged
If (CInt(lvwTemplateCategory.SelectedItems.Count.ToString) = 0) Then
Return
End If
Dim DirTempCatDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString
Dim DirTempInfo As New DirectoryInfo(DirTempCatDir)
lvwTemplates.Items.Clear()
Try
For Each TplFile As FileInfo In DirTempInfo.GetFiles
If Not (TplFile.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If Path.GetExtension(TplFile.Name) = ".spck" Or Path.GetExtension(TplFile.Name) = ".buspck" Then
lvwTemplates.Items.Add(TplFile.Name)
End If
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplate(sender As Object, e As EventArgs) Handles lvwTemplates.SelectedIndexChanged
If (CInt(lvwTemplates.SelectedItems.Count.ToString) = 0) Then
cmdQuickConfigure.Enabled = False
Return
End If
cmdQuickConfigure.Enabled = True
Dim TemplFileName As String = Path.GetFileNameWithoutExtension(lvwTemplates.SelectedItems(0).Text.ToString)
Dim DirTempDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString & "\" & TemplFileName
Dim imagePath As String = DirTempDir & ".png"
If File.Exists(imagePath) Then
picTemplateImage.ImageLocation = (imagePath)
picTemplateImage.SizeMode = PictureBoxSizeMode.StretchImage
picTemplateImage.Load()
Else
picTemplateImage.Image = picTemplateImage.ErrorImage
End If
txtModelName.Text = lvwTemplates.SelectedItems(0).Text.ToString
End Sub
Private Sub VisualViewControl(sender As Object, e As EventArgs) Handles cmdVisualControl.Click
If splCreateNewModel.Panel2Collapsed = False Then
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
cmdVisualControl.Text = ">>"
Else
cmdVisualControl.Text = "<<"
splCreateNewModel.Panel2Collapsed = False
Size = New Size(1300, 800)
End If
End Sub
Private Sub BrowseDirectory(sender As Object, e As EventArgs) Handles cmdBrowseDirectory.Click
Try
Dim sfd As New SelectFolderDialog With {
.Title = "Select a folder"
}
If sfd.ShowDialog(Me) = DialogResult.OK Then
txtModelDirectory.Text = sfd.FolderName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DialogOK(sender As Object, e As EventArgs) Handles cmdOk.Click
CreateModel()
Close()
End Sub
Private Sub DialogCancel(sender As Object, e As EventArgs) Handles cmdCancel.Click
Close()
End Sub
End Class

the connection property has not been initialized

I'm trying to run this code for my user interfaces, I connected the interface with my database and I did everything correctly. But the problem is this error keeps showing and I have no clue in how to fix it.
The error says "the connection property has not been initialized"
And this is my code,
Public Class ManageBus
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
txtbus.Text = Nothing
txtdriver = Nothing
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
End
End Sub
Private Sub btnadd_Click(sender As Object, e As EventArgs) Handles btnadd.Click
Try
OracleConnection1.Open()
Dim command As String
command = "insert into BUS(Bus_ID, Driver_ID)" _
& " values('" & txtbus.Text & "', '" _
& txtdriver.Text & ")"
OracleDataAdapter1.InsertCommand.CommandText = command
lblsql.Text = command
OracleDataAdapter1.InsertCommand.ExecuteNonQuery()
MsgBox("Insert Successful", MsgBoxStyle.Information, "Insert Status")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
OracleConnection1.Close()
End Try
End Sub
You need to initialize the connectionstring for the connection to setup the connection. For example:
Dim OracleConnection1 As New OracleConnection("Data Source=ORCL;User Id=test;Password=test;");
OracleConnection1.Open();

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

How to add BackgroundWorker for this code?

I've the following code, it's a code that parses an external Log file to a datagridview, however when I load a big file the operation takes time and the form freezes for a bit, what I need is to show a progress bar while it's parsing the log file.
This is the code :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using Reader As New Microsoft.VisualBasic.FileIO.
TextFieldParser(TextBox1.Text)
Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(Convert.ToInt32(txtDate.Text), Convert.ToInt32(txtTime.Text), Convert.ToInt32(txtExt.Text), Convert.ToInt32(txtCO.Text), _
Convert.ToInt32(txtNumber.Text), Convert.ToInt32(txtDuration.Text), Convert.ToInt32(txtAccCode.Text))
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
Dim curRowIndex = dg1.Rows.Add()
' Set the first cell of the new row....
dg1.Rows(curRowIndex).Cells(0).Value = currentRow(0)
dg1.Rows(curRowIndex).Cells(1).Value = currentRow(1)
dg1.Rows(curRowIndex).Cells(2).Value = currentRow(2)
dg1.Rows(curRowIndex).Cells(3).Value = currentRow(3)
dg1.Rows(curRowIndex).Cells(4).Value = currentRow(4)
dg1.Rows(curRowIndex).Cells(5).Value = currentRow(5)
dg1.Rows(curRowIndex).Cells(6).Value = currentRow(6)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
MsgBox("Total records imported : " & dg1.RowCount)
lblTotal.Text = "Total Records: " & dg1.RowCount
End Using
Catch
MsgBox("Invalid file, please make sure you entered the right path")
End Try
End Sub
Add a BackgroundWorker and set its WorkerReportsProgressProperty to True.
Add a ProgressBar.
Then try this code out:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim widths() As Integer = { _
Convert.ToInt32(txtDate.Text), Convert.ToInt32(txtTime.Text), Convert.ToInt32(txtExt.Text), _
Convert.ToInt32(txtCO.Text), Convert.ToInt32(txtNumber.Text), Convert.ToInt32(txtDuration.Text), _
Convert.ToInt32(txtAccCode.Text)}
ProgressBar1.Visible = True
ProgressBar1.Style = ProgressBarStyle.Marquee ' continuos animation
Dim input As New Tuple(Of String, Integer())(TextBox1.Text, widths)
BackgroundWorker1.RunWorkerAsync(input)
Catch ex As Exception
MessageBox.Show("Invalid Width!")
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim input As Tuple(Of String, Integer()) = DirectCast(e.Argument, Tuple(Of String, Integer()))
Try
Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(input.Item1)
Reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(input.Item2)
Dim currentRow() As String
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
BackgroundWorker1.ReportProgress(-1, New Object() { _
currentRow(0), currentRow(1), currentRow(2), _
currentRow(3), currentRow(4), currentRow(5), _
currentRow(6)})
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MessageBox.Show("Line is not valid and will be skipped." & vbCrLf & vbCrLf & ex.Message)
End Try
End While
End Using
Catch
MsgBox("Invalid file, please make sure you entered the right path")
End Try
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Dim values() As Object = DirectCast(e.UserState, Object())
dg1.Rows.Add(values)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Total records imported : " & dg1.RowCount)
lblTotal.Text = "Total Records: " & dg1.RowCount
ProgressBar1.Style = ProgressBarStyle.Continuous
ProgressBar1.Visible = False
End Sub