Undefined object reference for an object instance (which is not null)

Asked

Viewed 46 times

2

I am trying to show the amount of free space of a drive (the C:) but I get the error "Additional information: Undefined object reference for an instance of an object".

When I use a MessageBox to show the free space it returns in bytes the value without problems, but when trying to assign the value to a Label I get the error. The code is as follows::

private void SetMainPage()
{
    DriveInfo C = new DriveInfo("C");
    espacoHD.Text = C.TotalFreeSpace.ToString();
}
  • This error clearly indicates that it is null. Your test must be different from this.

  • So why Messagebox.Show(C.Totalfreespace) manages to return the value?

  • 1

    Either the mistake isn’t there or it’s different, there’s no other way.

  • 1

    If Messagebox works, it’s because espacoHD is void.

1 answer

0

Possibly the space HD is null. It follows code I did and it worked.

DriveInfo C = new DriveInfo("C");

Label espacoHD = new Label();
espacoHD.Text = C.TotalFreeSpace.ToString();
  • Now I don’t get Exception, but the Label is invisible as if it has no value.

  • I get it, what must be happening is that your label name is not exactly the same as what’s in the code. C# is case and minuscule sensitive. If the name is not the same, you can remove the line Label espacoHD = new Label(); . Not to miss the label name. use this.nomedalabel.Text

Browser other questions tagged

You are not signed in. Login or sign up in order to post.