在我的組合框中我展示一些主機名,如果我要到另一臺主機添加到組合框,我打開一個新的形式來添加它,當我點擊保存主機按鈕新主機是寫在一個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表單?那裏你應該把刷新邏輯 –