Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 数组问题-NullReferenceException未处理-VB.NET_Arrays_Vb.net - Fatal编程技术网

Arrays 数组问题-NullReferenceException未处理-VB.NET

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

我基本上是试图创建一个数组,将选中的项目导出到word文档中。但是我有一个错误,说

“对象引用未设置为对象的实例。”

“引用的'SelectedMutualFunds'的值为'Nothing'

下面是我的代码:

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))
我是将该代码添加到按钮单击中还是替换已写入按钮单击中的一行?由于最初您没有为字符串数组指定任何长度,因此必须在现有按钮单击代码中添加重拨行。