在我的组合框中我展示一些主机名,如果我要到另一台主机添加到组合框,我打开一个新的形式来添加它,当我点击保存主机按钮新主机是写在一个txt文件,然后我运行一个方法,加载保存在组合框中的txt文件中的所有主机,问题是运行我的方法后组合框不刷新。
这是我的存档主机方法。
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);
}
这是刷新组合框的方法:
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";
}
}
不相关的问题里面,但为什么在地球上的呼叫后,为了避免一个局部变量和一个单独的代码行分开两次?不要试图不惜一切代价聪明,有时你会灼伤你的手指。 – Steve
你在哪里调用AddHost表单?那里你应该把刷新逻辑 –