arrays - VB.net classes - Object reference not set to an instance of an object? -


i'm working on application in vb giving me trouble. coming java , c++, class syntax vb peculiar. have main form, , class created called webelement. imported class mainform.vb , declared array of webelement's. when try set or name attribute of first element of array of 'webelement`'s, gives me error - "object reference not set instance of object?" mean, , how fix it?

code
mainform.vb

imports myprogram.webelement  public class mainform      private webpage(0 9) webelement     private pagenum integer = 0      private sub openfile() handles opentoolstripmenuitem.click         webpage(pagenum).setname("rawr")         msgbox(webpage(pagenum).getname())     end sub  end class 

webelement.vb

public class webelement      private name string      public function setname(byref n string)         name = n     end function      public function getname()         return name     end function  end class 

this line

 private webpage(0 9) webelement 

declares array of 10 elements should of type webelement.
no element present in array. every slot nothing (null in c#).
calling method on null element give nullreferenceexception

you should check element before calling method and, if null, create element , assign required slot

private sub openfile() handles opentoolstripmenuitem.click     if webpage(pagenum) nothing        webpage(pagenum) = new webelement()     end if     webpage(pagenum).setname("rawr")     msgbox(webpage(pagenum).getname()) end sub 

as side note, why don't try use net syntax implement class properties

public class webelement      private name string     public property name() string                     return name         end         set(byval value string)             name = value         end set     end property end class 

and use in code

 webpage(pagenum).name = "rawr"  messagebox.show(webpage(pagenum).name) 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -