簡體   English   中英

VB.NET:將字符串數組添加到數組

[英]VB.NET: Adding an array of string to an array

Module globalVariable

    Public tblScItem As New DataTable
    Public tempArray()
    Public index As Integer
    Public stringArr() As String

End Module

Private Sub txtQty_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtQty.TextChanged

    stringArr = New String() {"", txtItem.Text, Form2.cbGondola.SelectedItem, txtQty.Text, DateTime.Now, Form1.txtLoginId.Text}

    If txtItem.Text <> Nothing And txtQty.Text <> Nothing Then

        index = 0

        tempArray(index) = stringArr

        tblScItem.Rows.Add(tempArray)

        index += 1

    End If

End Sub

我的程序是一個盤點程序,其工作方式是,當輸入物料數量時,它將顯示在數據網格中,同時存儲在數組中。 整個事務完成后,整個數組將導出到txt文件。

我聲明了一個數組stringArr來存儲該項目的所有詳細信息。 然后,我使用了tempArray來存儲每個項目(它在tempArray的各個索引中包含stringArr中的所有詳細信息。

Example: 
tempArray(0) = 'details of item 1 obtained from stringArr
tempArray(1) = 'details of item 2 obtained from stringArr
and so on

但是,輸入數量后,我不斷收到“對象未設置為對象的實例”的信息。

有人知道為什么嗎? 我需要幫助。

謝謝。

您收到錯誤消息是因為尚未初始化tempArray變量。 它只是對數組的引用,但沒有要引用的數組。

但是,您嘗試將數組放入數組中,但是DataRowCollection.Add方法采用數組,而不是數組數組。

只需使用stringArr變量:

Private Sub txtQty_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtQty.TextChanged

  stringArr = New String() {"", txtItem.Text, Form2.cbGondola.SelectedItem, txtQty.Text, DateTime.Now, Form1.txtLoginId.Text}

  If txtItem.Text <> "" And txtQty.Text <> "" Then

    tblScItem.Rows.Add(stringArr)

  End If

End Sub

請注意,控件的Text屬性從不為Empty ,您應該檢查它是否為空字符串。

如果要將行添加到DataTable以外的集合中,則不會使用數組,因為它無法調整大小。 您將使用List(Of String())

Public tempList As new List(Of String())

Private Sub txtQty_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtQty.TextChanged

  stringArr = New String() {"", txtItem.Text, Form2.cbGondola.SelectedItem, txtQty.Text, DateTime.Now, Form1.txtLoginId.Text}

  If txtItem.Text <> "" And txtQty.Text <> "" Then

    tempList.Add(stringArr)

    tblScItem.Rows.Add(stringArr)

  End If

End Sub

為什么要使用DataGrid和數組? 只需使用datagrid並在數據表上調用Rows(0).ItemArray

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM