-1

On Windows 7 when running my program i get an error saying "Object reference is not set to an object".

On Windows 8.1 it runs perfectly fine. I have narrowed it down to a single line causing this:

label14.Text = process["UserName"].ToString();

If i remove this line, it wont give any errors in Windows 7. I can also just do a label14.Text = "Dummytext"; and it works.

Maybe its something to do with the foreach statement but its working just fine with the other variables and the username is working on Windows 8.1.

Any tips?

foreach (ManagementObject process in searcher.Get())
{
    //print system info 

    process.Get();
    label6.Text = process["Manufacturer"].ToString() + " " + process["Model"].ToString();
    double Ram_Bytes = (Convert.ToDouble(process["TotalPhysicalMemory"]));
    label14.Text = process["UserName"].ToString();
    label12.Text = "" + (Math.Round(Ram_Bytes / 1073741824, 2)) + " GB";
}
Sayse
  • 42,633
  • 14
  • 77
  • 146
Johnny
  • 108
  • 1
  • 9
  • 3
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Jeroen Vannevel Feb 18 '15 at 09:24
  • It seems process["UserName"] int Windows 8.1 is not null but in Windows 7 its null. You can avoid the error by checking process["UserName"] == null . But you have to check what else you can use instead of process["UserName"] where it is missing – Adil Feb 18 '15 at 09:28
  • Add `if(process.ContainsKey("xyz"))` before using this entry – DrKoch Feb 18 '15 at 09:31

1 Answers1

1

You first have to check either prcess["UserName"] is null or not. Then typecast it to string

if (prcess["UserName"] != null)
{
    label14.Text = process["UserName"].ToString();
}
Muhammad Umar
  • 3,761
  • 1
  • 24
  • 36