2012-07-09 45 views
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#!)?

+1

在該行放置一個斷點並檢查item.SubItems.Count。 – 2012-07-09 22:02:34

回答

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"); 
+0

我添加了這些語句並發現問題。我所要做的只是將「if(listView1.Columns.Length <3)」更改爲「if(listView1.Columns.Count <3)」 – PaeneInsula 2012-07-09 22:59:27

+0

@ user994179啊對不起 - 通常是其中之一 – 2012-07-10 04:56:58