【问题标题】:Listview Item is always nullListview 项目始终为空
【发布时间】:2015-03-17 15:17:52
【问题描述】:

我正在尝试使用此代码使用一些注册表信息填充列表视图。

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("DisplayName") 返回null,然后在ToString 崩溃。

标签: c# winforms


【解决方案1】:

不要使用key.GetValue("Publisher").ToString(),而是使用(string)key.GetValue("Publisher")。这是因为GetValue 可以返回 null,如果您尝试将 .ToString() 设置为 null,您将得到该异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2011-05-10
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多