Label - 未将对象引用设置为对象的实例C#

时间:2015-02-18 09:24:05

标签: c# winforms

在运行我的程序的Windows 7上,我收到一条错误消息"对象引用未设置为对象"。

在Windows 8.1上,它运行得很好。 我把它缩小到一行导致了这个:

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

如果我删除此行,它将不会在Windows 7中出现任何错误。我也可以执行label14.Text = "Dummytext";并且它可以正常工作。

也许它与foreach语句有关,但它与其他变量配合得很好,用户名正在Windows 8.1上运行。

任何提示?

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";
}

1 个答案:

答案 0 :(得分:1)

首先,您必须检查prcess["UserName"]是否null。然后将其强制转换为string

if (prcess["UserName"] != null)
{
    label14.Text = process["UserName"].ToString();
}
相关问题