从另一种形式刷新组合框 [英] Refreshing combobox from another form

查看:81
本文介绍了从另一种形式刷新组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的组合框中,我显示了一些主机名,如果我想向组合框中添加其他主机,我会打开一个添加新表单,当我点击保存主机按钮时,新主机被写入txt文件中,然后我运行一种方法来加载组合框中txt文件上保存的所有主机,问题在于组合框是运行我的方法后没有刷新。

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.

这是我保存的方法。

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"; 

    }
}


推荐答案

这是一个经典问题

这些行不符合您的想法

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

这里是 mainForm的 NEW 实例创建完毕,并为该实例调用 loadHost 方法。受调用影响的组合是新实例拥有的组合,而不是在 mainForm 的第一个实例上可见的组合。

当然,新实例是隐藏的(您永远不会为其调用Show),因此您什么也看不到。

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.

要解决该问题,您应该使用事件通知或将mainForm的第一个实例传递给您的 addHost 表单。 (我不知道第二种形式的确切名称,因此在下面的示例中将其命名为 addHost ,将其更改为真实名称)。

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.

首先在全局级别的addHost表单内声明一个事件。

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);
....

最后,在您的mainForm中,创建完addHost实例将事件设置为mainForm内部的事件处理程序代码

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();
}

这篇关于从另一种形式刷新组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆