winforms - c# - "NullReferenceException was unhandled" but List isn't null -
i'm trying listbox (albumslistbox) list in list (albumlist).
albumlist , albumslistbox both created on form formmain. new album (with album.name defined in nametextbox.text on formalbumac) created go albumlist on form formalbumac.
from i've seen, making albumslist datasource of albumslistbox seems right way go. error "nullreferenceexception unhandled, object reference not set instance of object" when run program.
ln 16 of formalbumac excerpt occurs.
formmain.albumslistbox.datasource = musiccollection.formmain.publicvars.albumlist; i don't understand why happening, since message box before point shows albumlist.count = 1, ablumlist isn't null?
what doing wrong? right way achieve want? how can fix this? advice appreciated, thank you.
form formalbumac:
private formmain formmain; public formalbumac(formmain callerinstance) { initializecomponent(); formmain = callerinstance; } private void buttonsave_click(object sender, eventargs e) { if (musiccollection.formmain.publicvars.albumlist.count != 100) { musiccollection.formmain.publicvars.albumlist.add(new album(nametextbox.text)); messagebox.show("new album added: " + nametextbox.text); messagebox.show(musiccollection.formmain.publicvars.albumlist.count.tostring()); formmain.albumslistbox.datasource = musiccollection.formmain.publicvars.albumlist; this.close(); } else { messagebox.show("no room new album."); this.close(); } } form formmain:
public const int max_albums = 100; public formmain() { initializecomponent(); } private void buttonaddalbum_click(object sender, eventargs e) { formalbumac addalbumform = new formalbumac(this); addalbumform.showdialog(); } public static class publicvars { public static list<album> albumlist { get; set; } static publicvars() { albumlist = new list<album>(max_albums); } } public listbox albumlistbox { { return albumlistbox; } }
the local variable private formmain formmain; has never been initialized.
, null when use on failing line.
you trying use information stored statically in class formmain through instance variable of type formmain. variable null , cannot access data.
you remove error using
formmain = new formmain(); formmain.albumslistbox.datasource = musiccollection.formmain.publicvars.albumlist; .... but @ point think have other problems because local instance of formmain not same instance of formmain that, suppose, has created current instance of formalbumac
if assumption correct, need pass instance of formmain creates formalbumac inside class.
private formmain formmain; public formalbumac(formmain callerinstance) { initializecomponent(); formmain = callerinstance; } and then, somewhere in formmain, when construct formalbumac
.... formalbumac album = new formalbumac(this); album.showdialog(); ....
Comments
Post a Comment