问题很奇怪。我有一个表单(Form1.vb
),带有一个按钮(Button1
),一个ListView(ListView_orders
)和一个BackgroundWorker(BackgroundWorker1
)。我有一个名为(Functions.vb
)的模块文件,其中包含一些Sub。这些Sub a为BackgroundWorker1在需要时调用。
问题是当BackgroundWorker1在函数模块中调用Sub时,如何将项添加到ListView_orders。我知道现在很难理解我。告诉问题的另一种方法是" Functions.vb模块中的Sub用于向ListView_orders添加项目。当BackgroundWorker1调用此Sub时,它不会向ListView_orders"添加任何项目。
PS
这是我的代码:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
ListView_orders.Items.Add(ListView_orders.Items.Count + 1).SubItems.AddRange({"directrun", "b", "c"})
End Sub
Public Delegate Sub terminalAddInvoker(ctrl As Object)
Public Sub terminalAdd(ctrl As Object)
If ctrl.InvokeRequired Then
ctrl.Invoke(New terminalAddInvoker(AddressOf terminalAdd), ctrl)
Else
Dim item As New ListViewItem(CStr(ctrl.Items.Count + 1))
item.SubItems.AddRange({"a", "b", "c"})
ctrl.Items.Add(item)
End If
End Sub
Public Sub Adder(ctrl As Object)
terminalAdd(ctrl)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
addthings()
terminalAdd(ListView_orders) 'works (backgroundworker, calls the invoke delegate method)
Adder(ListView_orders) 'works (backgroundworker, call a sub which calls the invoke delegate method)
End Sub
End Class
Module Functions
Public Sub addthings() 'sub called from backgroundworker
Form1.ListView_orders.Items.Add("Hello") 'doesnt work (directly)
Form1.terminalAdd(Form1.ListView_orders) 'doesnt work (calls the invoke delegate method of Form1)
terminalAdd(Form1.ListView_orders) 'doesnt work (calls the invoke delegate method in the same file)
Form1.Adder(Form1.ListView_orders) 'doesnt work (calls a sub in Form1 which calls the invoke delegate method in Form1)
End Sub
Public Delegate Sub terminalAddInvoker(ctrl As Object)
Public Sub terminalAdd(ctrl As Object)
If ctrl.InvokeRequired Then
ctrl.Invoke(New terminalAddInvoker(AddressOf terminalAdd), ctrl)
Else
Dim item As New ListViewItem(CStr(ctrl.Items.Count + 1))
item.SubItems.AddRange({"a", "b", "c"})
ctrl.Items.Add(item)
End If
End Sub
End Module
在BackgroundWorker1_DoWork()
中,有3行代码。其中两个向ListView_orders添加了一个项目,但addthings()
Sub不会添加任何项目。在addthings()
Sub中,有4行代码试图将项添加到ListView_orders,但是没有它们可以工作。 应该添加项目。。线程仍然是一样的。仅仅因为它在不同的文件中,它不起作用。
请帮忙。