2013-04-13 36 views
1

爲什麼下面粘貼的代碼會拋出一個空引用異常?因爲我似乎無法找出原因。我看不到這是如何給我一個nullref異常

注:文本框有正確的名稱&當我收到異常時它們不是空的。

我的代碼:(我已經強調了與錯誤的行)

txtGuid.BackColor = Color.White 
    txtName.BackColor = Color.White 
    If txtGuid.Text <> "" And txtName.Text <> "" Then 
     Dim name As String = txtName.Text 
     Dim guid As String = txtGuid.Text 
     **frmWhitelist.names.Add(name)** 
     frmWhitelist.guids.Add(guid) 
     Me.Close() 
    Else 
     If txtGuid.Text = "" Then 
      txtGuid.BackColor = Color.Red 
     End If 
     If txtName.Text = "" Then 
      txtName.BackColor = Color.Red 
     End If 
     lblError.Text = "Please check your input in the red-colored fields." 
    End If 

調用堆棧:

> DayZAdminApp.exe!DayZAdminApp.inptBoxWhitelist.btnOk_Click(Object sender, System.EventArgs e) Line 15 + 0x3d bytes Basic

在調試中,在txtGuid.texttxtName.text都有文本值我當地人選項卡。

PS:如果這是由於我試圖將項目添加到另一個窗體上的公共var,我該如何解決這個問題?

PPS:本frmWhitelist.namesfrmWhitelist.guids被宣佈爲:

Public names, guids As List(Of String)

+0

你能告訴我們哪一個有NullReferenceException?您可以使用調試器附帶的 – Kenneth

+0

'frmWhitelist.names.Add(name)'< - 該行輕鬆檢查該行。 – Yorrick

+0

我想然後frmWhitelist或它的名稱集合爲null爲null。它在哪裏創建? – Kenneth

回答

2

的名單Nothing因爲你還沒有初始化他們。

所以你在這裏得到一個異常:

frmWhitelist.names 

這就避免了異常:

Public names As New List(Of String) 
Public guids As New List(Of String) 

你只是宣佈他們在這裏:

Public names, guids As List(Of String) 

他們仍然Nothing在此即使它們被宣佈也是如此。

+0

對,我是個白癡,我知道我應該這樣做,但我不記得爲什麼,謝謝:) – Yorrick

+0

你仍然需要將其分配到的名稱集合:frmWhitelist.names =名稱 frmWhitelist.guids = guid – Kenneth

+0

@Kenneth:我不明白。這兩個列表都以不同的形式聲明。 OP想在這裏添加字符串'frmWhitelist.names.Add(name)'。 –

相關問題