Results 1 to 4 of 4

Thread: If ListBox1.Items(0).ToString = Nothing Then

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2011
    Posts
    467

    If ListBox1.Items(0).ToString = Nothing Then

    Hi i keep getting an error here and cant seem to fix it :/

    VB CODE
    Code:
        Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
    
            If ListBox1.Items(0).ToString = Nothing Then
                MsgBox("this is nothing")
            Else
                MsgBox("something is there")
            End If
    
        End Sub
    ERROR:
    System.ArgumentOutOfRangeException was unhandled
    Message="InvalidArgument=Value of '0' is not valid for 'index'. Parameter name: index"

    Now i know that the error means that there there is nothing in "0" but my code above should check that but its not :/

    What have i done wrong ?

    Thanks for any help

  2. #2
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: If ListBox1.Items(0).ToString = Nothing Then

    Try: If ListBox1.Items.Count = 0 Then

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,422

    Re: If ListBox1.Items(0).ToString = Nothing Then

    vb Code:
    1. If ListBox1.Items.Count = 0 then
    2.    'no items

  4. #4
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: If ListBox1.Items(0).ToString = Nothing Then

    The actual problem is you are calling .ToString on ListBox1.Items(0).

    When Listbox1.items(0) is nothing, you can't call a method on it, because its not a valid instance of an object.

    Code:
     Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
    
            If ListBox1.Items(0) is Nothing Then
                MsgBox("this is nothing")
            Else
                MsgBox("something is there")
            End If
    
        End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width