当我从另一个实例调用方法idload()
时,它不会更新它应该的列表视图列表。我知道该方法正在调用正确,因为我在idload()
中的每个语句后都放了一个MessageBox
,并且显示了它。如果idload()
被称为Form2.cs
[它的形式]它工作正常,但如果我从Form4.cs
调用它,它不会更新列表视图。从另一个实例调用方法时,listview不会更新
我使用MessageBox.Show(xmlReader.GetAttribute("id"));
,当idload()
从Form2.cs
被调用时,它循环遍历xml中的每个id一次并按预期更新列表视图。当它从Form4.cs
被调用时,它遍历所有内容两次,不更新列表视图。
这里是代码的相关部分:
Form4.cs
public void myMethod()
{
Form2 form2 = new Form2();
form2.idload();
}
public void idwrite()
{
XElement xml = XElement.Load("settings.xml");
xml.Add(new XElement("Chat",
new XAttribute("id", textBox1.Text),
new XAttribute("name", textBox2.Text)));
xml.Save("settings.xml");
myMethod();
this.Close();
}
Form2.cs
public void idload()
{
listView1.Items.Clear();
XmlReader xmlReader = XmlReader.Create("settings.xml");
while (xmlReader.Read())
{
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Chat"))
{
if (xmlReader.HasAttributes)
{
// listView1.Items.Add(xmlReader.GetAttribute("id"));
// listView1.Items.Add(xmlReader.GetAttribute("name"));
string[] arr = new string[4];
ListViewItem itm;
arr[0] = (xmlReader.GetAttribute("id"));
arr[1] = (xmlReader.GetAttribute("name"));
itm = new ListViewItem(arr);
MessageBox.Show(xmlReader.GetAttribute("id"));
listView1.Items.Add(itm);
}
}
}
xmlReader.Close();
}
这里是项目如果需要的话:https://ufile.io/8dc20
真的很困惑,为什么会出现这种情况,因为在调试时没有错误,所以任何帮助都不胜感激。
谢谢。
通常的误解。在你的代码中你创建了一个Form2的NEW实例,你正在调用那个实例上的方法,而不是已经显示的实例。尝试在调用idload之后调用form2.Show,然后您会看到您在不同实例上的更改 – Steve
@Steve哦谢谢我没有意识到这一点。有没有办法在初始表单上进行更改,而不是第二个表单上的更改? – Venomz