2012-05-26 40 views
0

爲什麼我得到這個異常?VB.NET拋出「對象引用未設置爲對象的實例」異常

未將對象引用設置爲對象的實例。

有了:

wb.Document.GetElementById("formfieldv1").InnerText = "some value" 

哪裏wbWebBrowser控件的名稱。

這裏是所有代碼:

Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click 
Dim strFrom As String = txtFrom.Text 
Dim strTo As String = txtTo.Text 
Dim strMsg As String = txtMsg.Text 
wb.Document.GetElementById("formfieldv1").InnerText = strFrom ' strFrom fills fine 
End Sub 

更新

正如意見建議我修改後的代碼是這樣的:

Dim doc = wb.Document 

    If (doc Is Nothing) Then 
    MsgBox("doc is nothing") 
    End If 


    Dim el = wb.Document.GetElementById("formfieldv1") 

    If (el Is Nothing) Then 
    MsgBox("el is nothing") 
    Else 
    el.InnerText = strFrom 
    End If 

有了,我越來越el is nothing 。我現在如何解決這個問題?


另外,如果你們能幫助我走出這將解決我的問題太多:

How to fill html form using web browser control

+2

「wb」爲「Nothing」,「Document」爲「Nothing」或文檔中不存在「formfieldv1」元素。 – Oded

+0

分步驟分解。 「Document」或「GetElementById()」的結果都爲空。 –

+0

@Oded:'wb'被放在窗體上,我可以在輸入時看到它的成員。同樣''formfieldv1'也可以在這裏看到freesmscraze.com的'From'字段 – Dev555

回答

2

我想這就是爲什麼它是很好的業務分解爲若干個很好的例子而不是嘗試在一行中執行很多操作,尤其是當可以返回空值時。

如果你把wb.Document.GetElementById("formfieldv1").InnerText = "some value"

,並把它分解成

var document = wb.Document; 
var element = document.GetElementById("formfieldv1"); 
element.InnerText = "some value"; 

當異常被拋出,這將是更明顯的是什麼失敗。單步執行代碼時,檢查每個操作的結果也更容易。從彙編的角度來看,它沒有什麼區別,它最終會被編譯到同一個IL。

我認爲在單行代碼中儘可能多地做出自然願望,但我認爲在許多情況下它會傷害可讀性和調試能力。

+0

有一個實際上我沒有注意到的iframe,這要感謝Tony在上面的評論中發現的。儘管感謝您的回答。 – Dev555

相關問題