earl chester siaotong
earl chester siaotong

Reputation: 103

NullReferenceException fix?

Im new with vb.net and I know i still got a lot to learn. Research and lots of sample codes help me improve my programming skill but then theres still alot of things to be confused about.

Here's an error I just encountered.

Dim drv As DataRowView
    If e.RowIndex >= 0 Then
        If e.RowIndex <= ds.Tables("entrancequestion").Rows.Count - 1 ***Then***
                                                                          'Object reference not set to an instance of an object.
            drv = ds.Tables("entrancequestion").DefaultView.Item(e.RowIndex)
            Dim c As Color
            If drv.Item("TimesAnswered").Value <= (Convert.ToDouble(lblappcount.Text) * 0.2) Then

                c = Color.Yellow
            ElseIf drv.Item("TimesAnswered").Value >= (Convert.ToDouble(lblappcount.Text) * 0.8) Then
                c = Color.Red
            Else
                c = Color.Black
            End If
            e.CellStyle.ForeColor = c
        End If
    End If

this was written under the DataGridView.Cellformatting event. basicly i just wanted to changethe rows text color on the datagridview along those conditions.

  1. row forecolor changes to yellow if "TimesAnswered" is less than or equal to 20% of the value on lblappcount.text.
  2. row forecolor changes to redif "TimesAnswered" is less than or equal to 80% value on lblappcount.text.
  3. and row for color if conditions above was not satisfied.

any suggestions is greatly appreciated.

Upvotes: 1

Views: 149

Answers (2)

earl chester siaotong
earl chester siaotong

Reputation: 103

Got it. Here's what I did. under the Cell formatting event I wrote this one.

  For i As Integer = 0 To EntranceQuestionDataGridView.Rows.Count - 1
        If EntranceQuestionDataGridView.Rows(i).Cells(10).Value <= (Convert.ToDouble(lblappcount.Text) * 0.2) And EntranceQuestionDataGridView.Rows(i).Cells(10).Value > 0 Then
            EntranceQuestionDataGridView.Rows(i).DefaultCellStyle.BackColor = Color.Red
        ElseIf EntranceQuestionDataGridView.Rows(i).Cells(10).Value >= (Convert.ToDouble(lblappcount.Text) * 0.8) Then
            EntranceQuestionDataGridView.Rows(i).DefaultCellStyle.BackColor = Color.Yellow
        Else
            EntranceQuestionDataGridView.Rows(i).DefaultCellStyle.BackColor = Color.White
        End If
    Next

Thanks anyways guys. I learned lots of stuff :)

Upvotes: 0

Crono
Crono

Reputation: 10478

Either ds is null or it does not contains a table named entrancequestion.

Use a little Assert magic here:

Debug.Assert(ds IsNot Nothing)

Dim tblEntranceQuestion As DataTable = ds.Tables("entrancequestion")

Debug.Assert(tblEntranceQuestion IsNot Nothing)

If e.RowIndex <= tblEntranceQuestion.Rows.Count - 1
    (...)

Upvotes: 2

Related Questions