2016-07-22 55 views
-2

林有一個問題想處理ArgumentNullExeption發生VB.net零誤差

值不能是空

paramiter名項目

到目前爲止,香港專業教育學院嘗試了以下

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     Dim ArgumentNullException As New Boolean 
     If (ListBox2.Items.Add(ListBox1.SelectedItem.ToString = "")) Then 
      MessageBox.Show("please pick from list", "error") 
     End If 
     ListBox1.Items.Remove(ListBox1.SelectedItem) 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     Dim ArgumentNullException As New Boolean 
     If (ListBox2.Items.Add(ListBox1.SelectedItem Is Nothing)) Then 
      MessageBox.Show("please pick from list", "error") 
     End If 
     ListBox1.Items.Remove(ListBox1.SelectedItem) 


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     Dim ArgumentNullException As New BooleanListBox2 
     ListBox2.Items.Add(ListBox1.SelectedItem) 
     If (ListBox1.SelectedItem) = "" 
      MessageBox.Show("please pick from list", "error") 
     ListBox1.Items.Remove(ListBox1.SelectedItem) 

A ND錯誤仍然出現任何人都可以幫助請

更新時間:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
      ListBox2.Items.Add(ListBox1.SelectedItem) 
      If IsNothing (ListBox1.SelectedItem) 
       MessageBox.Show("please pick from list", "error") 
      ListBox1.Items.Remove(ListBox1.SelectedItem) 

給出錯誤仍然

+0

這是更好地爲您粘貼整個相關的代碼,比如List變量的初始化。 – PSo

+0

究竟是這樣的:'If(ListBox2.Items.Add(ListBox1.SelectedItem.ToString =「」))Then' ?? –

+0

Noob試驗和錯誤 – shaggs

回答

4

的問題是不太清楚,但我會試試看。


當你的應用程序有Listboxes並使用.SelectedItem屬性你應該總是使用try/catch語句,甚至更好檢查,如果用戶選擇和項目:

If IsNothing(ListBox1.SelectedItem) Then Exit Sub 

你也可以使用

If ListBox1.SelectedItems.Count = 0 Then Exit Sub 

您也可以使用If/Else,但將該語句放在代碼的第一行使得它在我看來更具可讀性。

使用此代碼將使您的按鈕什麼都不做,當沒有選定的項目。 否則,你可以使用多,如果把一個MsgBox("Please pick an Item"),警告用戶:

If IsNothing(ListBox1.SelectedItem) Then 
    MsgBox("Please pick an Item first.") 
    Exit Sub 
End If 
// Your Code after that 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    // Leave the Sub and Message the User, when there is no SelectedItem 
    If IsNothing(ListBox1.SelectedItem) Then 
     MsgBox("Please pick an Item first.") 
     Exit Sub 
    End If 
    // Code will only reach here, when there is a SelectedItem 
    ListBox2.Items.Add(ListBox1.SelectedItem) 
    ListBox1.Items.Remove(ListBox1.SelectedItem) 
End sub 
+0

我的目標是讓消息框出現,如果用戶只是按下按鈕,而不選擇一個項目 – shaggs

+0

謝謝你缺少* end sub * – shaggs

+0

很高興我能幫上忙。永遠記住:您打開的所有東西都需要在某處關閉:If/End if,While/EndWhile,Function/End Function,Sub/End Sub,Select Case/End Select,(...) – Luke