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
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.