【问题标题】:VB.NET nullReferenceException UnhandledVB.NET nullReferenceException 未处理
【发布时间】:2017-03-12 03:14:13
【问题描述】:

我无法将问题(txtQuestion.Text)添加到 dataGridView 但如果您添加相同的问题,它会起作用并显示 MessageBox.Show(“您不能输入相同的问题。”)。添加数据是我唯一的问题。

Dim qID As String
        rnd.Next(0, 99999)
        For Each row As DataGridViewRow In UsersDBDataGridView.Rows
            If txtQuestion.Text = row.Cells(1).Value.ToString Then '<-- NullReferenceException was unahandled.
                MessageBox.Show("You cant enter the same Question.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                valid = True
                Exit For
            Else
                valid = False
            End If
        Next
        If cbxDifficulty.Text = "Easy" Then
            diff = "E"
            diffValue = 5
        ElseIf cbxDifficulty.Text = "Average" Then
            diff = "A"
            diffValue = 10
        ElseIf cbxDifficulty.Text = "Difficult" Then
            diff = "D"
            diffValue = 20
        End If
        qID = diff & "-" & Date.Now.Date.ToString("ddMMMyyyy").ToUpper & "-" & rnd.ToString("00000")
        If valid = False Then
            Me.UsersDBTableAdapter.Add(qID, txtQuestion.Text, txtAnswer.Text, diffValue)
            Me.UsersDBTableAdapter.Fill(Me.UsersDBDataSet.UsersDB)
        End If

【问题讨论】:

标签: database vb.net datagridview datagrid


【解决方案1】:

您需要在If 语句中为Value 属性添加一个空检查。

If row.Cells(1).Value IsNot Nothing AndAlso txtQuestion.Text = row.Cells(1).Value.ToString Then

我只想指出:使用= 运算符比较字符串没有错

事实上,the equality operator 调用 String.Equals() 进行比较:

该运算符依次调用静态 Equals(String, String) 方法,该方法执行序数(区分大小写和不区分区域性)比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多