我在这里尝试了所有用户的方法,但似乎没有一个对我有用。 我想在vb.net中从Form2更新Form1中的ListView,但是当我启动此方法时没有任何反应。
Public Sub checkFoundList()
For Each item In myListView.Items
If Not File.Exists(item.SubItems(2).Text) Then
myListView.Items.Remove(item)
End If
Next
End Sub
此方法在Form1上,当我在此处启动它时,它工作正常。但是,如果我从Form2调用它,它就不会。
在Form2中,我只需用:
调用它Form1.checkFoundList()
我还尝试将修饰符Public设置为myListView
,但仍然不起作用。此外,一些用户解释的方法如使用事件也不起作用。真的很奇怪。
ListView是一个特殊控件吗?
答案 0 :(得分:1)
您将遇到的一个问题是,您正在使用For Each
语句枚举列表中的项目。删除项目时会出现问题。
而是使用For
语句向后进行枚举,以便在删除项目时索引不会移位:
Public Sub checkFoundList()
For i = myListView.Items.Count - 1 To 0 Step -1
Dim item As <TypeTheListViewHolds> = myListView.Items(i)
If Not File.Exists(item.SubItems(2).Text) Then
myListView.Items.RemoveAt(i)
End If
Next
End Sub
我刚刚调整了您提供的代码(不知道myListView
持有什么),但无论数据类型如何,方法都是相同的。
关于从Form2
调用它,请确保从 checkFoundList
的实例中调用Form1
。类似的东西:
' Class variable in Form2 which has an instance of Form1.
Private _form1 As Form1
' New Form2 method.
' Pass an instance of Form1 to the constructor of Form2.
' This way this instance of Form2 will "know" about a Form1 object.
Public Sub New(form1Object As Form1)
' Initialization code.
' Set the reference to Form1 in Form2
_form1 = form1Object
End Sub
Public Sub Form2Method()
_form1.checkFoundList
End Sub
答案 1 :(得分:0)
如上所述,看到您收到的错误会很有帮助。但这很可能是因为Form2没有对Form1的引用。解决此问题的方法之一是将Form2的所有者设置为Form1。
在Form1中创建Form2时,设置其所有者:
Dim f2 As Form2 = New Form2()
f2.Owner = Me
f2.ShowDialog()
在Form2中获取对Form1的引用并访问列表框,在这种情况下我访问一个简单的文本框:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim f1 As Form1 = DirectCast(Me.Owner, Form1)
f1.TextBox1.Text = "Hello World"
End Sub