2012-01-19 88 views
1

這是我sample.htmlC#的NullReferenceException

<html> 
    <head> 
     <title>Test</title>  
    </head> 
    <body> 
     <div id="testingID">hello</div> 
    </body> 
</html> 

內,我有這樣的代碼在C#中,我想提示與該DIV元素的世界「你好」裏面ID testingID

private void btnGetData_Click(object sender, EventArgs e) 
    { 
     string url = string.Format("{0}/sample.html", Environment.CurrentDirectory); 
     WebBrowser webb = new WebBrowser(); 

     webb.Navigate(url); 

     var doc = webb.Document; 
     HtmlElement elem = doc.GetElementById("testingID"); 
     MessageBox.Show(elem.InnerText); 
    } 

,但我得到對象引用不設置到對象的實例。 on MessageBox.Show(elem.InnerText);

這裏一點幫助..

回答

4

也許,你正試圖訪問元素,但文檔此時不加載。在WebBrowser.DocumentCompleted事件中移動doc.GetElementById("testingID");,它應該工作。

+0

感謝老闆..它就像一個魅力..:d –

+0

很高興我能夠幫助:-) – Davita

1

我假設elem爲null,因爲在文檔中找不到ID爲'testingID'的元素。嘗試使用調試器進行調試,並驗證elem不爲null。或者,你可以試試下面的:

if (elem != null) 
{ 
    MessageBox.Show(elem.InnerText); 
} 
else 
{ 
    MessageBox.Show('No element found!'); 
}