Advertisement
ficho2604

Untitled

Apr 18th, 2023
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 25.14 KB | None | 0 0
  1. Imports System.IO
  2. Imports System.Runtime.InteropServices
  3. Imports System.Text
  4. Imports System.Windows.Forms
  5. Imports Excel = Microsoft.Office.Interop.Excel
  6.  
  7. Public Class Form1
  8.     Private savedFilePaths As New Dictionary(Of String, String)()
  9.     Private folderPaths As New Dictionary(Of String, String)()
  10.     Private fileDict As New Dictionary(Of String, String)()
  11.     Private excelDataCache As New Dictionary(Of String, List(Of List(Of String)))()
  12.     Private WithEvents excelApp As Excel.Application
  13.     Private openExcelInstances As New List(Of Excel.Application)()
  14.  
  15.  
  16.     Private Sub SaveFilePathsToFile()
  17.         Dim filePath As String = Path.Combine(Application.StartupPath, "selected_files.txt")
  18.  
  19.         Using sw As New StreamWriter(filePath)
  20.             For Each item As String In ListBox1.Items
  21.                 Dim filePathForItem As String = savedFilePaths.FirstOrDefault(Function(kvp) kvp.Key = item).Value
  22.  
  23.                 If filePathForItem IsNot Nothing Then
  24.                     Dim line As New StringBuilder()
  25.                     line.Append(item).Append("|").Append(filePathForItem)
  26.                     sw.WriteLine(line.ToString())
  27.                 End If
  28.             Next
  29.         End Using
  30.     End Sub
  31.     Private Function GetFormattedRowData(row As Excel.Range, columnIndices As Dictionary(Of String, Integer), maxColumnWidths As Dictionary(Of String, Integer)) As String
  32.         Dim rowData As String = ""
  33.         For Each header As String In maxColumnWidths.Keys
  34.             If columnIndices.ContainsKey(header) Then
  35.                 Dim cell As Excel.Range = row.Cells(1, columnIndices(header))
  36.                 Dim cellValue As String = If(cell.Value IsNot Nothing, cell.Value.ToString(), "")
  37.                 rowData += cellValue.PadRight(maxColumnWidths(header) + 2)
  38.             End If
  39.         Next
  40.         Return rowData
  41.     End Function
  42.     Private Function PadCellValue(value As String, width As Integer) As String
  43.         Return value.PadRight(width)
  44.     End Function
  45.  
  46.     Private Sub DisplayExcelData(excelData As List(Of List(Of String)), dataGridView As DataGridView)
  47.         dataGridView.Rows.Clear()
  48.         For Each row As List(Of String) In excelData
  49.             If row.Count >= 4 Then
  50.                 dataGridView.Rows.Add(row(0), row(1), row(2), row(3))
  51.             End If
  52.         Next
  53.     End Sub
  54.  
  55.  
  56.     Private Function ReadAndCacheExcelData(filePath As String) As List(Of List(Of String))
  57.         Dim app As Excel.Application = New Excel.Application()
  58.         Dim wb As Excel.Workbook = app.Workbooks.Open(filePath)
  59.         Dim ws As Excel.Worksheet = Nothing
  60.  
  61.         For Each sheet As Excel.Worksheet In wb.Sheets
  62.             If sheet.Name = "Kabelliste" Then
  63.                 ws = sheet
  64.                 Exit For
  65.             End If
  66.         Next
  67.  
  68.         If ws Is Nothing Then
  69.             MessageBox.Show("Sheet 'data' not found in the selected Excel file.")
  70.             Return New List(Of List(Of String))()
  71.         End If
  72.  
  73.         Dim headers As String() = {"K", "C", "A", "D"}
  74.         Dim columnIndices As New Dictionary(Of String, Integer)
  75.  
  76.         For i As Integer = 1 To ws.UsedRange.Columns.Count
  77.             Dim cell As Excel.Range = ws.Cells(1, i)
  78.             Dim header As String = If(cell.Value IsNot Nothing, cell.Value.ToString(), "")
  79.             If headers.Contains(header) Then
  80.                 columnIndices(header) = cell.Column
  81.             End If
  82.         Next
  83.  
  84.         Dim cachedData As New List(Of List(Of String))()
  85.  
  86.         For i As Integer = 2 To ws.UsedRange.Rows.Count
  87.             Dim rowData As New List(Of String)()
  88.             For Each header As String In headers
  89.                 If columnIndices.ContainsKey(header) Then
  90.                     Dim cell As Excel.Range = ws.Cells(i, columnIndices(header))
  91.                     Dim cellValue As String = If(cell.Value IsNot Nothing, cell.Value.ToString(), "")
  92.                     rowData.Add(cellValue)
  93.                 End If
  94.             Next
  95.             cachedData.Add(rowData)
  96.         Next
  97.  
  98.         wb.Close(False)
  99.         app.Quit()
  100.  
  101.         ReleaseObject(ws)
  102.         ReleaseObject(wb)
  103.         ReleaseObject(app)
  104.  
  105.         Return cachedData
  106.     End Function
  107.  
  108.  
  109.  
  110.     Private Sub SaveExcelPaths()
  111.         Dim lines As New List(Of String)
  112.         For Each key As String In fileDict.Keys
  113.             lines.Add($"{key}={fileDict(key)}")
  114.         Next
  115.         File.WriteAllLines("excel.txt", lines)
  116.     End Sub
  117.     Private Sub LoadExcelPaths()
  118.         If Not File.Exists("excel.txt") Then
  119.             Return
  120.         End If
  121.  
  122.         Dim lines As String() = File.ReadAllLines("excel.txt")
  123.         For Each line As String In lines
  124.             Dim parts As String() = line.Split("=")
  125.             If parts.Length = 2 Then
  126.                 fileDict(parts(0)) = parts(1)
  127.             End If
  128.         Next
  129.     End Sub
  130.     Private Sub SaveExcelFilePath(key As String, filePath As String)
  131.         fileDict(key) = filePath
  132.         SaveExcelPaths()
  133.     End Sub
  134.  
  135.     Private selectedItem As String = ""
  136.  
  137.  
  138.     Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
  139.         If ListBox1.SelectedIndex <> -1 Then
  140.             selectedItem = ListBox1.SelectedItem.ToString()
  141.         End If
  142.     End Sub
  143.  
  144.     Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
  145.         If ListBox1.SelectedIndex <> -1 Then
  146.             OpenExcelFileDialog(ListBox1.SelectedItem.ToString())
  147.         End If
  148.     End Sub
  149.  
  150.  
  151.  
  152.  
  153.     Private Sub OpenExcelFileDialog(selectedItem As String)
  154.         Using openFileDialog As New OpenFileDialog()
  155.             openFileDialog.Filter = "Excel Files|*.xlsx;*.xls"
  156.             openFileDialog.Title = "Select an Excel File"
  157.  
  158.             If openFileDialog.ShowDialog() = DialogResult.OK Then
  159.                 Dim filePath As String = openFileDialog.FileName
  160.                 SaveExcelFilePath(selectedItem, filePath)
  161.                 excelDataCache(selectedItem) = ReadAndCacheExcelData(filePath)
  162.                 DisplayExcelData(excelDataCache(selectedItem), DataGridView1)
  163.             End If
  164.         End Using
  165.     End Sub
  166.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  167.         LoadPaths()
  168.         LoadFiles()
  169.         LoadExcelPaths()
  170.         Label1.Text = "Select harness from the list to show KAB."
  171.     End Sub
  172.     Private Sub RadioButton1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton1.Click
  173.         LoadFile("C:\Users\filip\Desktop\Harnesses\c2.txt")
  174.     End Sub
  175.  
  176.     Private Sub RadioButton2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton2.Click
  177.         LoadFile("C:\Users\filip\Desktop\Harnesses\PF.txt")
  178.     End Sub
  179.  
  180.     Private Sub RadioButton3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton3.Click
  181.         LoadFile("C:\Users\filip\Desktop\Harnesses\COMPONENTS.txt")
  182.     End Sub
  183.  
  184.     Private Sub radioButton1_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton1.CheckedChanged
  185.         If RadioButton1.Checked Then
  186.             RadioButton1_Click(sender, e)
  187.         End If
  188.     End Sub
  189.  
  190.     Private Sub radioButton2_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton2.CheckedChanged
  191.         If RadioButton2.Checked Then
  192.             RadioButton2_Click(sender, e)
  193.         End If
  194.     End Sub
  195.  
  196.     Private Sub radioButton3_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton3.CheckedChanged
  197.         If RadioButton3.Checked Then
  198.             RadioButton3_Click(sender, e)
  199.         End If
  200.     End Sub
  201.  
  202.     Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
  203.         If e.KeyCode = Keys.Enter Then
  204.             Dim searchText As String = TextBox1.Text.ToLower()
  205.             For i As Integer = 0 To ListBox1.Items.Count - 1
  206.                 Dim currentItem As String = ListBox1.Items(i).ToString().ToLower()
  207.                 If currentItem.Contains(searchText) Then
  208.                     ListBox1.SelectedIndex = i
  209.                     Exit For
  210.                 End If
  211.             Next
  212.         End If
  213.     End Sub
  214.     Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
  215.         If e.KeyCode = Keys.Enter Then
  216.             Dim searchText As String = TextBox2.Text.ToLower()
  217.             For i As Integer = 0 To ListBox2.Items.Count - 1
  218.                 Dim currentItem As String = ListBox2.Items(i).ToString().ToLower()
  219.                 If currentItem.Contains(searchText) Then
  220.                     ListBox2.SelectedIndex = i
  221.                     Exit For
  222.                 End If
  223.             Next
  224.         End If
  225.     End Sub
  226.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  227.         Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  228.  
  229.         ' Check if folder path is already set
  230.         If folderPaths.ContainsKey(selectedItem) Then
  231.             ' Ask user if they want to change the default folder location
  232.             Dim result As DialogResult = MessageBox.Show($"Are you sure you want to change the default folder location for {selectedItem}?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
  233.  
  234.             If result = DialogResult.Yes Then
  235.                 ' Prompt user to select a new folder location
  236.                 Using folderBrowser As New FolderBrowserDialog()
  237.                     folderBrowser.Description = $"Select a folder for {selectedItem}"
  238.  
  239.                     If folderBrowser.ShowDialog() = DialogResult.OK Then
  240.                         ' Update folder path and save to file
  241.                         folderPaths(selectedItem) = folderBrowser.SelectedPath
  242.                         SavePaths()
  243.                         MessageBox.Show($"Default folder location updated for {selectedItem}")
  244.                     End If
  245.                 End Using
  246.             End If
  247.         Else
  248.             ' If folder path is not set, inform user to double-click on the item
  249.             MessageBox.Show($"Please double-click on {selectedItem} to set the default folder location.")
  250.         End If
  251.     End Sub
  252.  
  253.     Private Sub OpenFolder(ByVal folderPath As String)
  254.         If folderPath <> "" Then
  255.             Try
  256.                 Process.Start("explorer.exe", folderPath)
  257.             Catch ex As Exception
  258.                 MessageBox.Show($"Error opening folder: {ex.Message}")
  259.             End Try
  260.         End If
  261.     End Sub
  262.  
  263.     Private Sub SavePaths()
  264.         Dim lines As New List(Of String)
  265.         For Each key As String In folderPaths.Keys
  266.             lines.Add($"{key}={folderPaths(key)}")
  267.         Next
  268.         File.WriteAllLines("paths.txt", lines)
  269.     End Sub
  270.  
  271.     Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
  272.         Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  273.  
  274.         ' Check if folder path is already set
  275.         If folderPaths.ContainsKey(selectedItem) Then
  276.             ' Open folder in File Explorer
  277.             Try
  278.                 Process.Start("explorer.exe", folderPaths(selectedItem))
  279.             Catch ex As Exception
  280.                 MessageBox.Show($"Error opening folder: {ex.Message}")
  281.             End Try
  282.             Return
  283.         End If
  284.  
  285.         ' If folder path is not set, ask user to select folder
  286.         Using folderBrowser As New FolderBrowserDialog()
  287.             folderBrowser.Description = $"Select a folder for {selectedItem}"
  288.  
  289.             If folderBrowser.ShowDialog() = DialogResult.OK Then
  290.                 ' Set folder path and open folder in File Explorer
  291.                 folderPaths(selectedItem) = folderBrowser.SelectedPath
  292.                 SavePaths()
  293.                 Try
  294.                     Process.Start("explorer.exe", folderBrowser.SelectedPath)
  295.                 Catch ex As Exception
  296.                     MessageBox.Show($"Error opening folder: {ex.Message}")
  297.                 End Try
  298.             End If
  299.         End Using
  300.     End Sub
  301.     Private Function GetSelectedRadioButton() As RadioButton
  302.         If RadioButton1.Checked Then
  303.             Return RadioButton1
  304.         ElseIf RadioButton2.Checked Then
  305.             Return RadioButton2
  306.         ElseIf RadioButton3.Checked Then
  307.             Return RadioButton3
  308.         Else
  309.             Return Nothing
  310.         End If
  311.     End Function
  312.     Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
  313.         Dim selectedRadioButton As RadioButton = GetSelectedRadioButton()
  314.  
  315.         If selectedRadioButton Is Nothing Then
  316.             MessageBox.Show("Please select a radio button")
  317.             Return
  318.         End If
  319.  
  320.         Dim filePath As String = Path.Combine("C:\Users\filip\Desktop\Harnesses", selectedRadioButton.Text & ".txt")
  321.         Dim textToWrite As String = TextBox1.Text & vbCrLf
  322.         File.AppendAllText(filePath, textToWrite)
  323.  
  324.         MessageBox.Show("Harness added to " & selectedRadioButton.Text)
  325.  
  326.         ListBox1.Items.Clear()
  327.         LoadFile(filePath)
  328.     End Sub
  329.  
  330.  
  331.     Private Sub SaveFiles()
  332.         ' Write the contents of the dictionary to the files.txt file
  333.         Dim lines As New List(Of String)()
  334.         For Each kvp As KeyValuePair(Of String, String) In fileDict
  335.             lines.Add(kvp.Key & "," & kvp.Value)
  336.         Next
  337.         File.WriteAllLines("files.txt", lines)
  338.     End Sub
  339.  
  340.     Private Sub LoadFiles()
  341.         ' Check if the files.txt file exists
  342.         If Not File.Exists("files.txt") Then
  343.             Return
  344.         End If
  345.  
  346.         ' Read the contents of the files.txt file and add the entries to the dictionary
  347.         Dim lines As String() = File.ReadAllLines("files.txt")
  348.         For Each line As String In lines
  349.             Dim parts As String() = line.Split(",")
  350.             If parts.Length = 2 Then
  351.                 fileDict(parts(0)) = parts(1)
  352.             End If
  353.         Next
  354.     End Sub
  355.     Private Sub LoadFile(filePath As String)
  356.         If Not File.Exists(filePath) Then
  357.             MessageBox.Show("File not found: " & filePath)
  358.             Return
  359.         End If
  360.         Dim lines As String() = File.ReadAllLines(filePath)
  361.         ListBox1.Items.Clear()
  362.         ListBox1.Items.AddRange(lines)
  363.     End Sub
  364.  
  365.     Private Sub LoadPaths()
  366.         If File.Exists("paths.txt") Then
  367.             Dim lines() As String = File.ReadAllLines("paths.txt")
  368.             For Each line As String In lines
  369.                 Dim parts() As String = line.Split("=")
  370.                 If parts.Length = 2 Then
  371.                     folderPaths(parts(0)) = parts(1)
  372.                 End If
  373.             Next
  374.         End If
  375.     End Sub
  376.     Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
  377.         ' Get the selected item from ListBox1
  378.         Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  379.  
  380.         ' Check if file location is already set
  381.         If fileDict.ContainsKey(selectedItem) Then
  382.             ' Open file using stored location
  383.             Try
  384.                 Dim startInfo As New ProcessStartInfo()
  385.                 startInfo.FileName = fileDict(selectedItem)
  386.                 startInfo.UseShellExecute = True
  387.                 Process.Start(startInfo)
  388.             Catch ex As Exception
  389.                 MessageBox.Show("Error opening file: " & ex.Message)
  390.             End Try
  391.             Return
  392.         End If
  393.  
  394.         ' If file location is not set, ask user to select file
  395.         Dim selectedFile As String = ""
  396.  
  397.         Using openFileDialog As New OpenFileDialog()
  398.             openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  399.             openFileDialog.Filter = "All Files (*.*)|*.*"
  400.             openFileDialog.FilterIndex = 1
  401.  
  402.             If openFileDialog.ShowDialog() = DialogResult.OK Then
  403.                 selectedFile = openFileDialog.FileName
  404.             End If
  405.         End Using
  406.  
  407.         ' Check if a file was selected
  408.         If String.IsNullOrEmpty(selectedFile) Then
  409.             MessageBox.Show("No file selected.")
  410.             Return
  411.         End If
  412.  
  413.         ' Set file location and save to file
  414.         fileDict(selectedItem) = selectedFile
  415.         SaveFiles()
  416.  
  417.         ' Open the file using the default application
  418.         Try
  419.             Dim startInfo As New ProcessStartInfo()
  420.             startInfo.FileName = selectedFile
  421.             startInfo.UseShellExecute = True
  422.             Process.Start(startInfo)
  423.         Catch ex As Exception
  424.             MessageBox.Show("Error opening file: " & ex.Message)
  425.         End Try
  426.     End Sub
  427.     Private Sub ListBox3_DragEnter(sender As Object, e As DragEventArgs) Handles ListBox3.DragEnter
  428.         If e.Data.GetDataPresent(DataFormats.FileDrop) Then
  429.             e.Effect = DragDropEffects.Copy
  430.         Else
  431.             e.Effect = DragDropEffects.None
  432.         End If
  433.     End Sub
  434.  
  435.     Private Sub ListBox3_DragDrop(sender As Object, e As DragEventArgs) Handles ListBox3.DragDrop
  436.         Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
  437.         For Each file In files
  438.             If Path.GetExtension(file) = ".xls" Or Path.GetExtension(file) = ".xlsx" Then
  439.                 ListBox3.Items.Add(file)
  440.             End If
  441.         Next
  442.     End Sub
  443.  
  444.     Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
  445.         If ListBox3.Items.Count < 1 Then
  446.             MessageBox.Show("Ubaci MACH liste!")
  447.             Return
  448.         End If
  449.         Dim app As Excel.Application = New Excel.Application()
  450.         app.Visible = False ' Make the Excel application visible
  451.  
  452.         Dim wb As Excel.Workbook = app.Workbooks.Add()
  453.         Dim ws As Excel.Worksheet = wb.Worksheets(1)
  454.  
  455.         ' Copy header row
  456.         Dim headerRange As Excel.Range = ws.Range("A1:CD1")
  457.         headerRange.Value = "Header"
  458.  
  459.         Dim rowCount As Integer = 2 ' Start copying data from second row
  460.         Dim headerCopied As Boolean = False
  461.         For Each file As String In ListBox3.Items
  462.             If Path.GetFileName(file) <> "Import-Export.xls" Then
  463.                 If Not headerCopied Then
  464.                     Dim wbHeader As Excel.Workbook = app.Workbooks.Open(file)
  465.                     Dim wsHeader As Excel.Worksheet = wbHeader.Worksheets("Data")
  466.                     Dim headerToCopy As Excel.Range = wsHeader.Range("A1", "CD1")
  467.                     headerToCopy.Copy()
  468.                     headerRange.PasteSpecial(Excel.XlPasteType.xlPasteAll)
  469.                     wbHeader.Close(False)
  470.                     headerCopied = True
  471.                 End If
  472.                 Try
  473.                     Dim wbCopy As Excel.Workbook = app.Workbooks.Open(file)
  474.                     Dim wsCopy As Excel.Worksheet = wbCopy.Worksheets("Data")
  475.                     Dim rangeToCopy As Excel.Range = wsCopy.Range("A2", "CD" & wsCopy.Range("A2").End(Excel.XlDirection.xlDown).Row)
  476.  
  477.                     rangeToCopy.Copy()
  478.                     Dim nextRow As Excel.Range = ws.Range("A" & rowCount)
  479.                     nextRow.PasteSpecial(Excel.XlPasteType.xlPasteAll)
  480.  
  481.                     rowCount += rangeToCopy.Rows.Count
  482.  
  483.                     ' Copy a blank cell
  484.                     wsCopy.Range("A1").Copy()
  485.  
  486.                     wbCopy.Close(False)
  487.  
  488.                     ' Clear the clipboard
  489.                     app.CutCopyMode = False
  490.                 Catch comEx As System.Runtime.InteropServices.COMException
  491.                     MessageBox.Show("An error occurred while processing the file: " & file & vbCrLf & "Error: The 'Data' worksheet was not found in the file.")
  492.                     Return
  493.                 Catch ex As Exception
  494.                     MessageBox.Show("An error occurred while processing the file: " & file & vbCrLf & "Error message: " & ex.Message)
  495.                     Return
  496.                 End Try
  497.             End If
  498.         Next
  499.         Dim columnRange As Excel.Range = ws.UsedRange.Columns
  500.         columnRange.AutoFit()
  501.         app.Visible = True
  502.         openExcelInstances.Add(app)
  503.         ExcelCheckTimer.Enabled = True
  504.         ExcelCheckTimer.Start()
  505.         AddHandler app.WorkbookBeforeClose, AddressOf WorkbookBeforeClose
  506.         excelApp = app
  507.         ' Release objects
  508.         ReleaseObject(ws)
  509.         ReleaseObject(wb)
  510.         ' Do not release the app object here since it will be released in the excelApp_WorkbookBeforeClose method
  511.     End Sub
  512.     Private Sub ExcelCheckTimer_Tick(sender As Object, e As EventArgs) Handles ExcelCheckTimer.Tick
  513.         If excelApp IsNot Nothing AndAlso IsNothing(excelApp.Workbooks) Then
  514.             ExcelCheckTimer.Stop()
  515.             ExcelCheckTimer.Enabled = False
  516.         Else
  517.             Return
  518.         End If
  519.  
  520.         ' If no Excel workbooks are open, quit the Excel application and release its resources
  521.         If excelApp IsNot Nothing Then
  522.             excelApp.Quit()
  523.             Marshal.ReleaseComObject(excelApp)
  524.             excelApp = Nothing
  525.         End If
  526.     End Sub
  527.  
  528.     Private Sub WorkbookBeforeClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean)
  529.         Dim app As Excel.Application = Wb.Application
  530.         Wb.Saved = True ' Mark the workbook as saved to prevent any save prompts
  531.         If app IsNot Nothing Then
  532.             app.Quit()
  533.             Marshal.ReleaseComObject(app)
  534.         End If
  535.     End Sub
  536.  
  537.     Private Sub App_WorkbookBeforeClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean)
  538.         Dim app As Excel.Application = Wb.Application
  539.         If app IsNot Nothing Then
  540.             app.Quit()
  541.             Marshal.ReleaseComObject(app)
  542.         End If
  543.     End Sub
  544.     Private Sub excelApp_WorkbookBeforeClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean) Handles excelApp.WorkbookBeforeClose
  545.         If excelApp IsNot Nothing Then
  546.             excelApp.Quit()
  547.             Marshal.ReleaseComObject(excelApp)
  548.             excelApp = Nothing
  549.         End If
  550.     End Sub
  551.  
  552.     Private Sub ReleaseObject(ByVal obj As Object)
  553.         Try
  554.             System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
  555.         Catch ex As Exception
  556.             Console.WriteLine("Error releasing object: " & ex.Message)
  557.         Finally
  558.             obj = Nothing
  559.             GC.Collect()
  560.         End Try
  561.     End Sub
  562.     Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
  563.         ListBox3.Items.Clear()
  564.     End Sub
  565.  
  566.     Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
  567.         ListBox2.Items.Clear()
  568.         Label1.Text = "Select harness from the list in order to show KAB list."
  569.     End Sub
  570.     Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
  571.         If ListBox1.SelectedIndex <> -1 Then
  572.             Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  573.  
  574.             If fileDict.ContainsKey(selectedItem) Then
  575.                 ListBox3.Items.Add(fileDict(selectedItem))
  576.             Else
  577.                 MessageBox.Show("Selected item does not have a file location.")
  578.             End If
  579.         Else
  580.             MessageBox.Show("Please select an item from the list.")
  581.         End If
  582.     End Sub
  583.  
  584.     Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
  585.         If ListBox1.SelectedIndex <> -1 Then
  586.             Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  587.  
  588.             If fileDict.ContainsKey(selectedItem) Then
  589.                 Dim filePath As String = fileDict(selectedItem)
  590.                 If File.Exists(filePath) Then
  591.                     If Not excelDataCache.ContainsKey(selectedItem) Then
  592.                         excelDataCache(selectedItem) = ReadAndCacheExcelData(filePath)
  593.                     End If
  594.                     DisplayExcelData(excelDataCache(selectedItem), DataGridView1)
  595.                 Else
  596.                     MessageBox.Show("File has been removed or moved! Double-click on the harness to select a new KAB list.")
  597.                 End If
  598.  
  599.                 Label1.Visible = True
  600.                 Label1.Text = $"KAB lista za: {ListBox1.SelectedItem}"
  601.             Else
  602.                 MessageBox.Show("Ovaj harness nema KAB listu! Double-click on the harness to select a KAB list.")
  603.             End If
  604.         Else
  605.             MessageBox.Show("Please select an item from the list.")
  606.         End If
  607.     End Sub
  608.     Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
  609.         If ListBox1.SelectedIndex <> -1 Then
  610.             Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  611.  
  612.             Dim openFileDialog As OpenFileDialog = New OpenFileDialog()
  613.             openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm"
  614.             openFileDialog.Title = "Select a KAB List Excel File"
  615.  
  616.             If openFileDialog.ShowDialog() = DialogResult.OK Then
  617.                 Dim newFilePath As String = openFileDialog.FileName
  618.  
  619.                 If fileDict.ContainsKey(selectedItem) Then
  620.                     fileDict(selectedItem) = newFilePath
  621.                 Else
  622.                     fileDict.Add(selectedItem, newFilePath)
  623.                 End If
  624.  
  625.                 MessageBox.Show("Location for " & selectedItem & " changed.")
  626.             End If
  627.         Else
  628.             MessageBox.Show("Please select a harness from the list.")
  629.         End If
  630.     End Sub
  631.  
  632. End Class
  633.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement