0

I can't add question(txtQuestion.Text) to the dataGridView but if you add the same question it works and shows MessageBox.Show("You can't enter the same question."). Adding data is my only problem.

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
Kilik Sky
  • 151
  • 1
  • 1
  • 12
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Enigmativity Mar 12 '17 at 03:36
  • Please remember to mark the answer that solved your problem as accepted. – Visual Vincent Mar 14 '17 at 07:34

1 Answers1

1

You need to add a null check to your If-statement for the Value property.

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

And I'd just like to point out: There's nothing wrong with using the = operator to compare strings.

Infact, the equality operator calls String.Equals() to perform the comparison:

The operator, in turn, calls the static Equals(String, String) method, which performs an ordinal (case-sensitive and culture-insensitive) comparison.

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75