2

我即将承认失败,我对 VB 还很陌生,我确信我已经设法错过了一些非常基本的东西,

我对以下代码的问题是,当执行 Button3_Click 函数时,如果我忘记在“ListBox2.Items. Add(test.Name)" 然后东西仍然会被吐到列表框中,所以假设那里有东西,

有什么帮助吗?

问候丹

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles
    Button3.Click

    Dim test As comdevice

    Dim usbcoms() As comdevice = FindComs()

    For Each test In usbcoms
        ListBox2.Items.Add(test.Name)
    Next


End Sub    


Private Function FindComs() As comdevice()
    Dim USBClass As New System.Management.ManagementClass("Win32_PNPEntity")
    Dim USBCollection As System.Management.ManagementObjectCollection =   
    USBClass.GetInstances()
    Dim USB As System.Management.ManagementObject
    Dim temp() As comdevice
    Dim n As Integer
    n = 0

    For Each USB In USBCollection
        If USB("Name").ToString().Contains("P") Then
            n += 1
        End If
    Next USB
    ReDim temp(n)

    n = 0
    For Each USB In USBCollection
        If USB("Name").ToString().Contains("COM") Then
            temp(n).Name = USB("Name").ToString()
            temp(n).DeviceID = USB("DeviceID").ToString()
        End If
    Next


    Return temp
End Function

Private Structure comdevice
    Public Name As String   ' This employee's given name.
    Public DeviceID As String   ' This employee's family name.
End Structure
4

2 回答 2

3

Your problems lies in the FindComs method.
The first loop search the USBCollection for devices that contains the letter P and you count them.
In the second loop, after dimensioning the return array with the number of devices found you try to fill this array with devices that contains the string COM, of course there is no relation between devices with COM and P in their name. You end up with an array bigger than the effective number of devices with COM in their name.

When the array returns, you add every slot of the array, but you have slots with NULL values and thus the error.
You can fix the problem dimensioning the array only for the devices with COM in their names

For Each USB In USBCollection
    If USB("Name").ToString().Contains("COM") Then
        n += 1
    End If
Next USB
ReDim temp(n)
于 2013-03-30T21:08:23.340 回答
2

Oded's comment is the most likely cause of this failure.

An easy test is to set the Name property to some default string, like "test" in your comdevice class.

That way, the Name property will never be null and you can see if it ever gets changed.

于 2013-03-30T21:10:39.933 回答