运行时发生的类型为“System.NullReferenceException”的未处理异常

时间:2016-03-09 07:43:28

标签: c#

每当我运行代码时,我都会收到此错误消息:

  

Picture-Resize.exe中出现未处理的“System.NullReferenceException”类型异常附加信息:对象引用未设置为对象的实例。

我的代码如下,这是为抓取网站而编写的:

         public partial class Form1 : Form
{
    List<string> mainitems = new List<string>();
    List<string> mainitems2 = new List<string>();
    List<string> address2 = new List<string>();
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        HtmlWeb hw = new HtmlWeb();
        doc = hw.Load("http://rahnama.com");
        HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"hierarchylist-title\"]");
        listBox1.Items.Clear();
        int j=0;
        foreach (var item in nodes)
        {
            mainitems.Add( item.InnerText);

         }
        for (int i = 0; i < mainitems.Count; i++)
        {
            listBox1.Items.Add(mainitems[i]);
            HtmlNodeCollection nodes2 = doc.DocumentNode.SelectNodes(string.Format("(//div[@class='hierarchylist-content'])[{0:D}]//div[@class='ch-link']", i+1));
            foreach (var item in nodes2)
            {
                mainitems2.Add(item.InnerText);

            }
            foreach (HtmlNode link in doc.DocumentNode.SelectNodes(string.Format("(//div[@class='hierarchylist-content'])[{0:D}]//div[@class='ch-link']//a[@href]", i + 1)))
            {
                // Get the value of the HREF attribute
                string hrefValue = link.GetAttributeValue("href", string.Empty);
                address2.Add(hrefValue);
            }
        }
        for (int i = 0; i < mainitems2.Count; i++)
        {
            listBox1.Items.Add(mainitems2[i]);
            listBox1.Items.Add(address2[i]);      
        }
        for (int i = 0; i < 51; i++)
        {
            doc = hw.Load(address2[i]);
            nodes = doc.DocumentNode.SelectNodes("//div[@class='hierarchylist-title2']");
            foreach (var item in nodes)
            {
                listBox2.Items.Add(item.InnerText);
            }
        }
    }

}

为什么我会收到此错误,我该如何避免? 这一行正在抛出异常:

foreach (var item in nodes) { listBox2.Items.Add(item.InnerText); }

0 个答案:

没有答案