Arrays 数组问题-NullReferenceException未处理-VB.NET
我基本上是试图创建一个数组,将选中的项目导出到word文档中。但是我有一个错误,说 “对象引用未设置为对象的实例。” 及 “引用的'SelectedMutualFunds'的值为'Nothing' 下面是我的代码:Arrays 数组问题-NullReferenceException未处理-VB.NET,arrays,vb.net,Arrays,Vb.net,我基本上是试图创建一个数组,将选中的项目导出到word文档中。但是我有一个错误,说 “对象引用未设置为对象的实例。” 及 “引用的'SelectedMutualFunds'的值为'Nothing' 下面是我的代码: Public Class ExportFunds Public SelectedMutualFunds() As String Private Sub ExportFundOkButton_Click(ByVal sender As System.Object, By
Public Class ExportFunds
Public SelectedMutualFunds() As String
Private Sub ExportFundOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportFundOkButton.Click
Dim i As Integer
Dim array_Counter As Integer
array_Counter = 0
For i = 0 To ExportFundCheckedListBox.Items.Count() - 1
If ExportFundCheckedListBox.GetItemCheckState(i) = CheckState.Checked Then
SelectedMutualFunds(array_Counter) = ExportFundCheckedListBox.Items(i).ToString
array_Counter += 1
End If
Next
Me.Close()
End Sub
有人能帮我解决这个问题吗?您需要提供字符串数组的长度
Public SelectedMutualFunds() As String
要在ExportFundOkButton_中执行以下操作,请在使用前单击,最好在for循环之前单击
Redim SelectedMutualFunds(ExportFundCheckedListBox.Items.Count() - 1)
您可以使用一行程序同时修复NullReference异常:
Private Sub ExportFundOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportFundOkButton.Click
SelectedMutualFunds = ExportFundCheckedListBox.Items.Where(Function(i) i.CheckState = CheckState.Checked).Select(Function(i) i.ToString()).ToArray()
Me.Close()
End Sub
或者,略长但更易于阅读:
Private Sub ExportFundOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportFundOkButton.Click
SelectedMutualFunds = ExportFundCheckedListBox.Items.
Where(Function(i) i.CheckState = CheckState.Checked).
Select(Function(i) i.ToString()).
ToArray()
Me.Close()
End Sub
没有证据表明,
SelectedMutualFunds
曾经实例化过,您只是声明了它。使用一个列表(字符串),您就不必担心数组的大小。我声明了列表(字符串),但现在它说该字符串不能转换为列表(字符串)SelectedMutualFundsList.Add(ExportFundCheckedListBox.Items(I))
我是将该代码添加到按钮单击中还是替换已写入按钮单击中的一行?由于最初您没有为字符串数组指定任何长度,因此必须在现有按钮单击代码中添加重拨行。