0

I am having trouble with a piece of sample code I am using in a Visual Basic project.

This is the sample:

 Dim dataRow As DataRow
 dataRow = dataSet.Tables(0).NewRow()

I am getting a NullReferenceException on the second line of the sample when I run it.

Any help is greatly appreciated!!!

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186

3 Answers3

1

The most likely explanation is that there is no table at index 0. It may also be that the datSet itself is null.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

Not certain as to what the intent of the code is, but from the looks of it you are trying to add a new row to a dataset? If that is the case, you would need declare a new data row and add it to the dataset. Alternatively you should be able to add a row to the dataset and then set datarow to the new row index.

J.Harrison
  • 11
  • 3
0

A DataSet is a collection of DataTables. I'm guessing that the DataTable reference has not yet been established and is not pointing to a DataTable object. Check whether the DataTable reference is null (Nothing in VB.NET) and if so, create a new DataTable object and add some columns to it. Then you will be able to add a new row as the DataTable reference will be pointing to a DataTable object that rows can be added to:

If IsNothing(dataset) = True Then
    dataset = New DataSet
    dataset.Tables.Add("Table1")
End If

If IsNothing(dataSet.Tables(0)) = True Then
    dataSet.Tables(0) = New DataTable
    dataSet.Tables(0).Columns.Add("FirstName", GetType(String))
    dataSet.Tables(0).Columns.Add("Surname", GetType(String))
    dataSet.Tables(0).Columns.Add("DateOfBirth", GetType(DateTime))
End If

Dim dataRow As DataRow = dataSet.Tables(0).NewRow
dataRow.Item("FirstName") = "John"
dataRow.Item("Surname") = "Smith"
dataRow.Item("DateOfBirth") = #11/30/1998#
dataSet.Tables(0).Rows.Add(dataRow)
Guru Josh
  • 566
  • 8
  • 16