add row to dataset

pol

New member
Joined
Mar 7, 2007
Messages
3
Programming Experience
Beginner
I Want to add a row in my dataset(dsStudent), i get an error:
An unhandled exception of type 'System.NullReferenceException' occurred in XMLFile2.exe

Additional information: Object reference not set to an instance of an object.

my code:
VB.NET:
Public Sub addStudent(ByVal nStundent As Student)
Dim DataRow1 As DataRow
 
DataRow1.Item("name") = CStr(nStundent.Naam) ' <- error in this line
DataRow1.Item("geboortedat") = CDate(nStundent.GeboorteDatum)
DataRow1.Item("email") = CStr(nStundent.Email)
DataRow1.Item("idNummer") = CInt(nStundent.Id)
 
dsStudent.Tables(0).Rows.Add(DataRow1)
 
End Sub
the dataset is filled with items from a XML file.

Thanks
POL
 
Last edited by a moderator:
You have declared a variable of type DataRow, but you have not created a new DataRow object and assigned to this variable. Normally you would use the New keyword to create a new object, but that is not how you do it with DataRows, instead use the NewRow function of the DataTable to return you a new DataRow object based on the columns of that table. So you insert this code after the variable declaration:
VB.NET:
DataRow1 = dsStudent.Tables(0).NewRow
Did you also know you can load the Xml file directly into a DataSet with its ReadXml method?
 
Thanks JohnH, Your solution solved my problem :)

Do I push my luck when I'm asking how i can remove a row out my dataset.
dsStudent.Tables(0).Rows.Romove(....Can i remove the row on index?

Thanks
POL
 
Use Rows.Remove method to remove a DataRow object, use RemoveAt method to remove a row by index.
 
DataSets dont contain rows, they contain DataTables (and DataTables contain rows). When you wrote your initial post, your text "I Want to add a row in my dataset" should be written: "I Want to add a row to the first datatable in my dataset"

Its a minor thing, but try to get used to using the correct names for stuff.. ;)



(And use row.Delete to marke a row as deleted; it will be removed next time AcceptChanges is called. It may also delete data from the backend database. Remove and REmoveAt will not delete data from a back end database)
 
Back
Top