尝试从第二种表单中删除ListView项时遇到问题。
例如,如果我在Form1上使用以下命令,它可以工作:
Listview1.SelectedItems(0).Remove
但是,如果我试图像这样从Form2中删除:
Form1.Listview1.SelectedItems(0).Remove
我收到以下错误: “无效的参数='0'的值对'index'无效。参数名称:索引”
然后我尝试从Form2上的listview获取一些项目,它给了我一个0的返回
Form1.Listview1.Items.Count
我不确定我的问题是什么。
更新
我已经发布了一个我的代码的简短示例(使用您的建议,因为我可以理解):
Private Sub ViewMessage()
Dim frm As New frmViewMailMessage
frm.Show()
End Sub
Public Sub DeleteItem(ByVal index As Integer)
lsvReceivedMessages.Items(index).Remove()
End Sub
Private instanceForm as frmShowMessages
Private Sub frmViewMailMessage_Load(sender As Object, e As EventArgs) Handles MyBase.Load
instanceForm = New frmShowMessages()
End Sub
Private Sub cmdDelete_Click(sender As Object, e As EventArgs) Handles cmdDelete.Click
instanceForm.DeleteItem(_index)
End Sub
希望我的代码可以帮助确定我的问题所在。
答案 0 :(得分:0)
在VB.net中,您通常会为每个Form
获取默认Form
个实例。您可能正在创建Form1
的实例,然后您尝试访问默认实例的ListView1
。
E.g。
Sub ButtonClick()
Dim f As New Form1()
f.Show()
' at this point if you access f's ListView you will get correct count
f.ListView1.Items.Count
' however if you try to access default instance it will NOT have any item
Form1.ListView.Items.Count
End Sub
这意味着您的实例f
不等于默认Form1
实例。
解决方案可以是,将f
变量作为类级变量并在任何地方使用它。或者,如果Form1
只有1个实例,那么您可以在任何地方使用默认实例。
我个人不会直接控制访问表单。我会创建一个Public
方法,该方法应该将数据作为列表返回给调用者,在本例中为Form2
。
更新-2:
根据您的情况,我正在为您简化一些事情,并使用Event
进行实施。
Public Class frmShowMessages
Private Sub btnOpenMessage_Click(sender As System.Object, e As System.EventArgs) Handles btnOpenMessage.Click
Dim frmView As New frmViewMessage(Me.ListView1.SelectedItems(0).Index)
AddHandler frmView.MessageDeleted, AddressOf DeleteMessageHandler
frmView.Show()
End Sub
Private Sub DeleteMessageHandler(sender As Object, e As frmViewMessage.MessageDeletedEventArgs)
Me.ListView1.Items.RemoveAt(e.MessageIndex)
End Sub
End Class
Public Class frmViewMessage
' a class which will be used for Event communication
Public Class MessageDeletedEventArgs
Inherits EventArgs
Public Property MessageIndex As Integer
Public Sub New(ByVal iIndex As Integer)
MyBase.New()
Me.MessageIndex = iIndex
End Sub
End Class
' main event which will alert the parent that a message deletion should be done
Public Event MessageDeleted As EventHandler(Of MessageDeletedEventArgs)
' private variable that will hold the MessageIndex
Private Property MessageIndex As Integer
' method that is responsible to raise event
Protected Overridable Sub OnMessageDeleted()
RaiseEvent MessageDeleted(Me, New MessageDeletedEventArgs(Me.MessageIndex))
End Sub
' we want to create this Form using the MessageIndex of ListView
Public Sub New(ByVal iMessageIndex As Integer)
Me.InitializeComponent()
Me.MessageIndex = iMessageIndex
End Sub
' the delete button will raise the event to indicate parent that
' a deletion of message should be done
Private Sub btnDelete_Click(sender As System.Object, e As System.EventArgs) Handles btnDelete.Click
Me.OnMessageDeleted()
End Sub
End Class