Confusion with the NEW keyword


New member
Mar 9, 2005
Programming Experience
Hello everyone, this is my first post here. I was hoping someone could help me out with a question that has been bugging me.

I'm working with ADO.NET and I have the following code (using untyped datasets):

Imports System.Data.SqlClient

PublicClass Form1

Inherits System.Windows.Forms.Form

Dim daStudentRec As New SqlDataAdapter
Dim cnDIYH As New SqlConnection
Dim cmStudentSelect As New SqlCommand
Dim dsStudents As New DataSet


PrivateSub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesMyBase.Load

Dim sConnectString AsString
Dim drStudent As DataRow
sConnectString = "server = 8001sbab1; database = DIYH; integrated security = SSPI"

cnDIYH.ConnectionString = sConnectString

With cmStudentSelect
.Connection = cnDIYH
.CommandText = "Select SSN,Lname,Fname from StudentRecord where left(SSN,1)='A'"

daStudentRec.SelectCommand = cmStudentSelect
drStudent = dsStudents.Tables(0).Rows(0)

txtSSN.Text = drStudent.Item("SSN")


This code works and the first SSN from the first record is displayed in the textbox. Simple, I know. Just wanted to learn and test things out.

The confusion I have is with the NEW keyword. Why is the NEW keyword required when declaring the data adapter,dataset,connection and command objects and not required when declaring the datarow in my Load procedure?
In fact, if I code the NEW keyword in that line, an error is generated. How come? Isn't the datarow also a class? How do I know when to use it and when not to (other than relying on Intellisense).
I belive the answer is that a datarow must belong to a table, and thus you can't create an indipendant row. You only need the NEW key work when you are creating a new instance of an object (such as your dataadapter), so you wouldn't need to assign new anyway as your assigning it an existing value ( dsStudents.Tables(0).Rows(0) ). If you want to creat a new row in the table you'd assign the datarow dsStudents.newrow.

Hope that makes things a little clearer.

Hmm..that makes sense. So if the class is a child of another class using the NEW keyword doesn't make sense because it can't exist on its own. Does that sound right?

Thanks for the info!
Well sort of. Think of it more as Datarow is part of datatable, than child. I wouldn't worry about it, it's one of those things you'll get used to...
One way is to look at the class and it's methods/properties in the object browser (press Ctrl+Alt+J). If it doesn't have a new method then there must be another way to instantiate the class.
With the dataRow, you must have a dataTable to create an instance of the class. You can either do as you did and set the dataRow variable to an existing row [dataSet.Tables(index).Row(index)] or you can use the dataTable.NewRow method to create a new dataRow.
Actually Paszt's I think you'll find Datarow does have a new method, however it's protected to stop you from calling it directly.