-2

我在尝试处理 ArgumentNullExeption时遇到问题

值不能为 Null

参数名称项

到目前为止,我尝试了以下

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)

仍然出现错误,请有人帮忙

更新:

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)

仍然给出错误

4

1 回答 1

4

问题很不清楚,但我会试一试。


当您的应用程序拥有Listboxes并使用该.SelectedItem属性时,您应该始终使用 Try/Catch 甚至更好地检查用户是否选择了项目:

If IsNothing(ListBox1.SelectedItem) Then Exit Sub

你也可以使用

If ListBox1.SelectedItems.Count = 0 Then Exit Sub

您也可以使用 If/Else,但在我看来,将语句放在代码的第一行会使其更具可读性。

当没有选定项目时,使用此代码将使您的按钮不执行任何操作。否则,您可以使用 multiline-If 放置一个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
于 2016-07-22T06:37:08.883 回答