Cannot add new row to datatable

Glitterati

Member
Joined
Mar 17, 2006
Messages
13
Programming Experience
Beginner
I am having problems adding new rows to a datatable. I was getting the error message "Object not set to an instance of an object." The answer seemed quite clear to me; create a new instance of the datarow object. After doing that I now get this error: "System.Data.DatRow.Protected Sub New not accessible in this context because it is 'Protected'".

Here is my code:

Imports System.Data.Sqlclient
Public Class AddBook
Inherits System.Windows.Forms.Form
Dim titCon As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\SQL Server 2000 Sample Databases\PUBS.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim pubAdapter As New SqlDataAdapter()
Dim comBuilder As New SqlCommandBuilder(pubAdapter)
Dim SQLtxt As New SqlCommand("Select title_ID, title, type,price,advance,royalty,pubdate,notes From titles", titCon)
Dim newTitles As New DataSet()
Dim tblTitles As New DataTable

'This is the part that throws the error
Dim newBookRow As New DataRow

Public Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

newBookRow = newTitles.Tables(
"Titles").NewRow()
newbookrow(
"title_id") = Me.txtTitle_ID.Text
newbookrow(
"title") = Me.txtTitle.Text

newTitles.Tables(
"Titles").Rows.Add(newbookrow)
pubAdapter.Update(
Me.newTitles)
pubAdapter.Fill(
Me.newTitles)
End Sub
End
Class

I'm a newbie at this (if you couldn't tell) so ANY help would be greatly appreciated!
 
Change
Dim newBookRow As New DataRow
To
Dim newBookRow As DataRow

When you use the New keyword, it tries to actualy create the object. The only way to instanciate the DataRow object though is through the use of the .NewRow method.

-tg
 
Did you load the table into your dataset? And did you give it the right name? (it's not in the code you posted).

-tg
 
Back
Top