using System.Runtime.CompilerServices; namespace Password_Manager { public delegate string SearchQuery(); public class PasswordListBox : ListBox { public event DataRequest? PathRequest; public event SearchQuery? SearchQueryRequest; public PasswordListBox(DataRequest PathRequest, SearchQuery? SearchQueryRequest = null) : base() { this.PathRequest = PathRequest; this.SearchQueryRequest = SearchQueryRequest; } public PasswordListBox() : base() { } /*do not instantiate this class using this constructor if you want to use the ReloadResults method afterwards. Use this so that the MainForm.Designer.cs file doesn't have a stroke due to Event References, then re-instantiate the object afterwards using the other constructor*/ public void ReloadResults(object? sender = null, EventArgs? arg = null) { DirectoryInfo d; FileInfo[] files = new FileInfo[0]; try { if (PathRequest != null) { d = new DirectoryInfo(PathRequest()); } else { throw new InvalidOperationException("You cannot use this method if you instantiated the object using the parameterless constructor"); } files = d.GetFiles("*.gpg"); } catch (ArgumentNullException e) { MessageBox.Show(e.ToString(), "Error: Invalid path", MessageBoxButtons.OK, MessageBoxIcon.Error); } string[] arrayTmp = new string[files.Length]; for (int i = 0; i < arrayTmp.Length; i++) { arrayTmp[i] = files[i].Name; } List elements = new List(arrayTmp); string[] copy = elements.ToArray(); string? searchQuery = SearchQueryRequest?.Invoke(); if (searchQuery != null) //we have a search query { foreach (string s in copy) { if (!s.Contains(searchQuery)) { elements.Remove(s); } } } this.DataSource = elements; } } }