简体   繁体   中英

Refreshing combobox from another form

sdfdfdfdf

In my combobox i display some host names, if i want to add another host to the combobox, i open a new form to add it, when i hit save host button the new host is written in a txt file, and after that i run a method that loads all the hosts saved on the txt file in the combobox, the problem is that the combobox is not refreshing after running my method.

THIS IS MY SAVE HOST METHOD.

private void btnSaveHost_Click(object sender, EventArgs e)
{
    if (textAlias.Text.Trim().Length > 0 && textHost.Text.Trim().Length > 0)
    {
        if (!Directory.Exists("C:\\MCDFC"))
        {
            Directory.CreateDirectory("C:\\MCDFC");

        }

        try
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\MCDFC\\Hosts.txt", true);
            file.WriteLine(textAlias.Text + "#" + textHost.Text);
            file.Close();
            file.Dispose();
            MessageBox.Show("Host saved", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
            textAlias.Text = "";
            textHost.Text = "";
            mainForm mf = new mainForm();
            mf.loadHosts();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    else
        MessageBox.Show("One or both fields are empty", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

}

And this is the method to refresh the combobox:

public void loadHosts()
{
    List<host> hosts = new List<host>();
    if (File.Exists("C:\\MCDFC\\Hosts.txt"))
    {
        string[] lines = System.IO.File.ReadAllLines(@"C:\\MCDFC\\Hosts.txt");

        for(int x =0;x<lines.Length;x++)
        {
            hosts.Add(new host(lines[x].Split('#')[0], lines[x].Split('#')[1]));
        }

        cmbHosts.DataSource = hosts;
        cmbHosts.DisplayMember = "aliasName";
        cmbHosts.ValueMember = "hostName"; 

    }
}

It is a classical problem

These lines don't do what you think

mainForm mf = new mainForm();
mf.loadHosts();

Here a NEW instance of mainForm is created and you call the loadHost method for that instance. The combo affected by the call is the one owned by the new instance, not the one visible on the first instance of mainForm .
Of course the new instance is hidden (you never call Show for it) so you don't see anything.

To solve it you should use event notifications or pass the first instance of mainForm to your addHost form. (I don't know the exact name of the second form, so I will name it addHost in the example below, change it to the real name).

I will show you how to use event notifications because I think is more Object Oriented than passing the first instance.

First declare an event inside the addHost form at the global level.

public class addHost: Form
{
    public delegate void OnAddHost(string host, string alias)
    public event OnAddHost HostAdded;
    ....

Now in the button click event raise this event if some external client has declared its interest subscribing to the event notification.

....
// Side note: using statement is the preferred way to handle disposable resources
// You don't need to call Close and Dispose, it is done automatically at the end of the using block
// The compiler add the required code and works also in case of exceptions
using(StreamWriter file = new System.IO.StreamWriter("C:\\MCDFC\\Hosts.txt", true))
{
     file.WriteLine(textAlias.Text + "#" + textHost.Text);
}
MessageBox.Show("Host saved", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
textAlias.Text = "";
textHost.Text = "";

// If someone subscribe to the event it will receive it...
HostAdded?.Invoke(textAlias.Text, textHost.Text);
....

And finally, in your mainForm, just after the creation of the addHost instance set the event to the event handler code inside the mainForm

// These lines goes where you open the addHost form
using(frmAddHost fa = new frmAddHost())
{
    fa.HostAdded += hostAddedHandler;
    fa.ShowDialog();
}
...
private void hostAddedHandler(string host, string alias)
{
    // I call loadHost but you can look at what has been added 
    loadHosts();
}

Try setting to null and then assign the new source,

  cmbHosts.DataSource = null;
  cmbHosts.DataSource = hosts;

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