0

我正在使用 WinForms/VS2010 c# 创建一个包含 12 列和 8 行的列表视图。这是 WinForms 自动编码文件的片段:

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.listView1 = new System.Windows.Forms.ListView();
       .....
    } 

然后,在 Form1.cs 文件中,我有以下方法:

    // in my form1.cs file
    public void listView1_Populate()
    {
        var columnIndex = listView1.Columns[2].Index;
        int counter = 0;

        foreach (ListViewItem item in listView1.Items)
        {
             if (item.SubItems[columnIndex].Text == "2")
             {
                 counter += 100;
                 item.SubItems[columnIndex].Text = counter.ToString(); 
             }
        }
    }

Object reference not set to an instance of an object但是当代码到达该行时, 我得到了异常:var columnIndex = listView1.Columns[2].Index;

我做错了什么(除了在 54 岁时尝试学习 c#!)?

4

1 回答 1

0

从您的问题中不清楚什么是空引用。但是,如果您在此行之前添加以下内容,var columnIndex = listView1.Columns[2].Index;您可能会更清楚地了解出了什么问题。

if (listView1 == null)
    throw new Exception("listView1 is null");
if (listView1.Columns == null)
    throw new Exception("Columns is null");
if (listView1.Columns.Length < 3)
    throw new Exception("Columns length is out of range");
于 2012-07-09T21:56:31.417 回答