访问listview列时的对象/实例异常

时间:2012-07-09 21:42:44

标签: c# winforms listview

我正在使用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#!)?

1 个答案:

答案 0 :(得分: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");