0

Hey all I am trying to figure out how to get the code below to work in VB.net. I already converted it from C# to VB.net:

Dim dt As New DataTable()
Dim dr As DataRow

dt.Columns.Add("Name")
dt.Columns.Add("Number")

For Each item As KeyValuePair(Of String, String) In vCardReader.dicNumName
    dr = dt.NewRow()
    dr(0) = item.Value
    dr(1) = item.Key
    dt.Rows.Add(dr)
Next

Me.Invoke(New MethodInvoker(
 Sub()
          contactNameNumList.DataSource = dt
          contactNameNumList.AllowUserToResizeRows = False
          contactNameNumList.AllowUserToResizeColumns = False
          contactNameNumList.AllowUserToOrderColumns = False
          contactNameNumList.CellBorderStyle = DataGridViewCellBorderStyle.None
          contactNameNumList.Columns(0).Width = 30
          contactNameNumList.Columns(1).Width = contactNameNumList.Width / 2 - 25
          contactNameNumList.Columns(2).Width = contactNameNumList.Width / 2 - 25
End Sub))

However, when I run the program, the error I get for the above code is this:

Object reference not set to an instance of an object.

How can I correct this error?

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
StealthRT
  • 10,108
  • 40
  • 183
  • 342

1 Answers1

0

How can I correct this error?

The short answer make sure your objects are initialized. I'll assume contactNameNumList is a DataGridView and dt is a DataTable. If you created either or both of these in code make sure you used the New keyword or initialized them with real data.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22
  • I have **Dim dt As New DataTable()** for the dt and does have values for it. The contactNameNumList is a DataGridView that was placed on the form itself. – StealthRT Apr 19 '14 at 05:16
  • You seem to be on the right track. **dt** doesn't seem to be holding its value each go around (see updated OP). The **dr** does have data each go around but it doesnt seem to be placed into the **dt**. – StealthRT Apr 19 '14 at 05:25
  • @StealthRT This has nothing to do with the internals of your datatable or datarows. I'm going by the line you mentioned the error occurring on. `contactNameNumList` is null when you're trying to assign a property of it. Either assign `contactNameNumList` before your code, or move your code to a place in the program flow where `contactNameNumList` is not null. If this is some kind of webforms or winforms app for example, make sure your code runs after any designer code that creates the grid and assigns it to `contactNameNumList`. – Asad Saeeduddin Apr 19 '14 at 06:35