Form Loading Error Message

Creative2

Freshman
Joined
Jan 7, 2003
Messages
31
Location
Toronto, Canada
Hi Again guys,

I have a list box on my form, I am trying to fill the listbox from database(by calling a sub) when form loads, which works fine, but when i try to set listbox's selected index to the first item, it gives me following error:

"Object Reference not set to an instance of an object", although after clicking the error message, it sets the index.

I wrote my codes in form_load event and I also tried to put em after InitializeComponent() call. I am getting same error.

Any idea to get over it?

Your help would be greatly appreciated.
 
Can you show us the code that fills the listbox and how you're setting the selected index?

Also, are you binding the listbox? I don't mean binding the drop-down portion, but binding the actual selected value (using control.DataBindings.Add(...)).

-nerseus
 
Like this:
Visual Basic:
 private sub FIllMyList()

Dim getPlatform As String
        getPlatform = "Select PartNumber from Drawings order by PartNumber"

        Dim i As Integer
        Dim Cmd As New SqlCommand(getPlatform, MyConn)
        Dim Rdr As SqlDataReader

        Rdr = Cmd.ExecuteReader
        Do While Rdr.Read
            lstDrawing.Items.Add(Rdr.GetString(0))
        Loop
        Rdr.Close()
        MyConn.Close()
end sub
Setting the index:

Mylist.selectedIndex=0

I call the same sub and set index in button_click event too, and it works fine, only doesnt work on form loading.

One more question though.

is there any way to find that form is loaded? or all the components are initialized? I wuz thinking if it is possible then I can check it first and then call my sub in form_load event.
 
Last edited by a moderator:
Well first things first. The constructor will get called before anything else in you code. The default constructor will call InitializeComponent which takes care of creating all controls (assuming you're not creating some on your own, but always using the designer). So any code referencing lstDrawing after InitializeComponent should be fine - including Form_Load.

If you ARE creating lstDrawing "by hand" - meaning your Dim'ing the variable in some routine such as FillMyList - then other subs, such as Form_Load, won't be able to reference lstDrawing.

If I draw a listbox on a form and try and set it's SelectedIndex to 0 in Form_Load, I get "Specified argument was out of the range of valid values" - still an error, but not the message you reported getting. Your message should only come if the variable lstDrawing isn't defined - never set to New.

Check where you define lstDrawing and make sure it's getting set to New in InitializeComponent.

-nerseus
 
No I am not making listbox in codes, its under the initializecomponents' codes, and I indexing listbox after the constructor initializecomponents() call, and it still showing me the same error. Anyway to find if form loaded? so i can index listbox after that.
 
Back
Top