简体   繁体   中英

C# Adding items to MainForm ListBox from a different class

I'm still fairly new to programming, and have started a project where I'm trying to seperate functionality of the program into classes, where each class handles most everything related to that specific part of the program.

I have one class, called DirectoryMonitors, that creates an object that monitors a directory with FileSystemWatcher. I'm trying to add items to a ListBox on the MainForm from an instance of this DirectoryMonitors class. However, it seems I'm unable to call the method in MainForm unless it's static - but if it's static, I can't access my ListBox.

Relevant part of my DirectoryMonitor class:

public class DirectoryMonitorData
{
    public bool WatcherActive { get; set; } = true;
    public string EQVersion { get; set; }
    public string FolderLocation { get; set; }
}

public class DirectoryMonitor : DirectoryMonitorData
{

    private void FolderWatcher_Changed(object sender, FileSystemEventArgs e)
    {
        FileInfo fi = new FileInfo(e.FullPath);
        if (!IsFileLocked(fi))
        {
            int startPos = e.FullPath.LastIndexOf("\\") + 1;
            int endPos = e.FullPath.IndexOf("-Inventory") - startPos;
            string character = e.FullPath.Substring(startPos, endPos);
            MessageBox.Show(character);

            string[] delimiters = { ControlChars.Tab.ToString() };
            using (TextFieldParser parser = Microsoft.VisualBasic.FileIO.FileSystem.OpenTextFieldParser(e.FullPath, delimiters))
            {
                // Process the file's lines.
                while (!parser.EndOfData)
                {
                    try
                    {
                        string[] fields = parser.ReadFields();
                        MainForm.addLogToListBox(fields[0]);
                        for (int i = 1; i <= 5; i++)
                        {

                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
    }

    private bool IsFileLocked(FileInfo file)
    {
     ...
    }
}

Relevant part of my MainForm class:

    public partial class MainForm : Form
{


    public MainForm()
    {
        InitializeComponent();
    }


    public void addLogToListBox(string logMessage)
    {
        logsListBox.Items.Insert(0, logMessage);
    }
}

UPDATED CODE:

    public FileSystemWatcher FolderWatcher = new FileSystemWatcher();

        public DirectoryMonitor()
        {
            FolderWatcher.NotifyFilter = NotifyFilters.LastWrite;
            FolderWatcher.Filter = "*-Inventory.txt";
            FolderWatcher.Changed += FolderWatcher_Changed;
        }

public void setupDirectoryMonitorList()
        {
            foreach (DirectoryMonitorData dmd in MainForm.directoryMonitorList)
            {
                DirectoryMonitor dm = new DirectoryMonitor()
                {
                    WatcherActive = dmd.WatcherActive,
                    FolderLocation = dmd.FolderLocation,
                    EQVersion = dmd.EQVersion
                };

                if (dm.WatcherActive)
                {
                    dm.FolderWatcher.Path = dm.FolderLocation;
                    dm.FolderWatcher.EnableRaisingEvents = true;
                    dm.FolderWatcher.NotifyFilter = NotifyFilters.LastWrite;
                    dm.FolderWatcher.Filter = "*-Inventory.txt";
                    dm.FolderWatcher.Changed += FolderWatcher_Changed;
                }
                MainForm.directoryMonitorObjects.Add(dm);
            }
        }

Add a property to your DirectoryMonitorData class and pass list box to it:

public class DirectoryMonitorData
{
    public bool WatcherActive { get; set; } = true;
    public string EQVersion { get; set; }
    public string FolderLocation { get; set; }
    public ListBox Logs {get; set;}
}

and then:

DirectoryMonitor monitor = new DirectoryMonitor  { Logs = logsListBox };

now in your class you can simply add anything to that listbox:

Logs.Items.Add(Something);

The way I normally do that is to add a constructor to the class, that takes a 'MainForm' parameter, then save the 'MainForm' parameter in a field.

public class DirectoryMonitor : DirectoryMonitorData
{

    public DirectoryMonitor(MainForm form)
    {
        this.mainForm = form;
    }

    private MainForm mainForm;

}

Now you can access all public methods an properties of MainForm by using the field mainForm .

Alternative :

Create an eventhandler in your class (with a custom EventArgs ). Then from your 'MainForm', subscribe to that event. Now the class does not have to know anything about the form. You just need to Invoke the eventhandler in your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM