C# Listview项始终为空
我正试图使用此代码用一些注册表信息填充listviewC# Listview项始终为空,c#,winforms,C#,Winforms,我正试图使用此代码用一些注册表信息填充listview private void button1_Click(object sender, EventArgs e) { ListViewItem lvItem = null; RegistryKey uninstallKey = Registry.LocalMachine.OpenSubKey(UninstallPath); if (uninstallKey != null) foreach (var su
private void button1_Click(object sender, EventArgs e)
{
ListViewItem lvItem = null;
RegistryKey uninstallKey = Registry.LocalMachine.OpenSubKey(UninstallPath);
if (uninstallKey != null)
foreach (var subKey in uninstallKey.GetSubKeyNames())
{
using (RegistryKey key = uninstallKey.OpenSubKey(subKey))
{
if (key != null)
{
lvItem =
new ListViewItem(key.GetValue("DisplayName").ToString());
lvItem.SubItems.Add(key.GetValue("Publisher").ToString());
}
}
listView1.Items.Add(lvItem);
}
}
}
调试应用程序时一切正常。在断点到达此处之前,不存在null
lvItem = new ListViewItem(key.GetValue("DisplayName").ToString());
lvItem.SubItems.Add(key.GetValue("Publisher").ToString());
应用程序崩溃并出现空指针异常。我知道这是一个愚蠢的问题,但我真的不明白它怎么会为空。不要使用
key.GetValue(“Publisher”).ToString()
,而是使用(string)key.GetValue(“Publisher”)
。这是因为GetValue
可以返回null,如果您尝试.ToString()
为null,您将得到该异常。我猜key.GetValue(“DisplayName”)
返回null
,然后它在ToString
崩溃。