vb.net connect to sql database and add a row

Hi,

This is my first vb .net project, so it's probably something simple.
When my code runs, I get the following error. (code pasted below)
The example was taken from msdn.

Thanks for any help offered.

The Error
-------------------------------------------------------------------------------------------------------------------------------

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll

Additional information: System error.
--------------------------------------------------------------------------------------------------------------------------------
'Start of code
        'ADD TO DB


        Dim sConnectionString As String


        ' Modify the following code to correctly connect to your SQL Server.
        sConnectionString = "Password=cue;User ID=cue;" & _
                            "Initial Catalog=Cue;" & _
                            "Data Source=pd100408"


        Dim objConn As New SqlConnection(sConnectionString)
        objConn.Open()

        ' Create an instance of a DataAdapter.
        Dim da As _
            New SqlDataAdapter("Select * From DH51", objConn)

        ' Create an instance of a DataSet, and retrieve data from the DH51 table.
        Dim ds As New DataSet("DH51")
        da.FillSchema(ds, SchemaType.Source, "DH51")
        da.Fill(ds, "DH51")

        '*****************
        'BEGIN ADD CODE
        ' Create a new instance of a DataTable.
        Dim tblDH51 As DataTable
        tblDH51 = ds.Tables("DH51")

        Dim drCurrent As DataRow
        ' Obtain a new DataRow object from the DataTable.
        drCurrent = tblDH51.NewRow()

        ' Set the DataRow field values as necessary.

        drCurrent("Unit Number") = strUnitNumber
        drCurrent("Enquiry Type") = strEnquiryType
        drCurrent("Record Type") = strRecordType
        'drCurrent("Report Usage") =
        drCurrent("Processing Status") = strProcessingStatus
        drCurrent("Creation Date") = strCreationDate
        drCurrent("Creation Time") = strCreationTime
        drCurrent("Cue Reference Number") = strCueReferenceNumber

        'Pass that new object into the Add method of the DataTable.Rows collection.
        tblDH51.Rows.Add(drCurrent)
        'MsgBox("Add was successful.")

        'END ADD CODE


        '*****************
        'BEGIN SEND CHANGES TO SQL SERVER

        Dim objCommandBuilder As New SqlCommandBuilder(da)
        da.Update(ds, "DH51")

        '07979 906888
        MsgBox("SQL Server updated successfully" & Chr(13) & "Check Server explorer to see changes")

        ' END SEND CHANGES TO SQL SERVER
LVL 1
andy_boothAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

andy_boothAuthor Commented:
Oops for to say, the line it falls over on is...

da.Update(ds, "DH51")
0
Arthur_WoodCommented:
you may need to make a single 'small' addition:

 Dim da As _
            New SqlDataAdapter("Select * From DH51", objConn)
 da.InsertCommand = new SQLCommand("Insert into DH51 (Unit Numner, Enquiry Type,Record Type,Processing Status,Creation Date,Creation Time,Cue Reference Number) VALUES(@UnitNumber, @EnquiryType,@RecordType,@ProcessingStatus,@CreationDate,@CreationTime,@CueReferenceNumber), objConn)
Dim workParm as sqlParameter

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@UnitNumber",sqlDbType.Int))
workParm.SourceColumn = "Unit Number"
workParm.SourceVersion = DataRowVersion.Current

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@EnquiryType",sqlDbType.Int)) ' or whatever type is relevant
workParm.SourceColumn = "Enquiry Type"
workParm.SourceVersion = DataRowVersion.Current

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@RecordType",sqlDbType.Int)) ' or whatever type is relevant
workParm.SourceColumn = "Record Type"
workParm.SourceVersion = DataRowVersion.Current

workParm = da.InsertCommand.Parameters.Add(New sqlParmeter("@ProcessingStatus",sqlDbType.Int)) ' or whatever type is relevant
workParm.SourceColumn = "Processing Status"
workParm.SourceVersion = DataRowVersion.Current

and so on for each of the fields in the record.

notice that it is a VERY VERY bad idea to have embeddied BLANKS in the names of either Tbales or Fields---  rename the Field "Unit Number' to either "UnitNumber" or "Unit_Number".

AW



0
Arthur_WoodCommented:
you should use the DataAdaper WIZARD for the first couple of applications, as it will build all of the UGLY code that you see above, for you, to build the necessary INSERT,DELETE and UPDATE commands for the DataAdapter.

AW
0
krznpskCommented:
Andy,

The code looks fine to me; the error is clearly occurring in your SqlConnection.

In case you didn't know, the DataAdapter object will implicitly OPEN your SqlConnection object, then CLOSE it when it's done with the Fill() method.

Anyway, the problem is kind of hard to identify right now because you're not really seeing the error message.  Do you know about Try/Catch blocks?  You should place your code in a Try/Catch so that you can at least see a more detailed error message.

Here is your code rewritten in a Try/Catch block... you'll see the only changes are one line at the top and three at the bottom.  Good luck!:

Try
        Dim sConnectionString As String


        ' Modify the following code to correctly connect to your SQL Server.
        sConnectionString = "Password=cue;User ID=cue;" & _
                            "Initial Catalog=Cue;" & _
                            "Data Source=pd100408"


        Dim objConn As New SqlConnection(sConnectionString)
        objConn.Open()

        ' Create an instance of a DataAdapter.
        Dim da As _
            New SqlDataAdapter("Select * From DH51", objConn)

        ' Create an instance of a DataSet, and retrieve data from the DH51 table.
        Dim ds As New DataSet("DH51")
        da.FillSchema(ds, SchemaType.Source, "DH51")
        da.Fill(ds, "DH51")

        '*****************
        'BEGIN ADD CODE
        ' Create a new instance of a DataTable.
        Dim tblDH51 As DataTable
        tblDH51 = ds.Tables("DH51")

        Dim drCurrent As DataRow
        ' Obtain a new DataRow object from the DataTable.
        drCurrent = tblDH51.NewRow()

        ' Set the DataRow field values as necessary.

        drCurrent("Unit Number") = strUnitNumber
        drCurrent("Enquiry Type") = strEnquiryType
        drCurrent("Record Type") = strRecordType
        'drCurrent("Report Usage") =
        drCurrent("Processing Status") = strProcessingStatus
        drCurrent("Creation Date") = strCreationDate
        drCurrent("Creation Time") = strCreationTime
        drCurrent("Cue Reference Number") = strCueReferenceNumber

        'Pass that new object into the Add method of the DataTable.Rows collection.
        tblDH51.Rows.Add(drCurrent)
        'MsgBox("Add was successful.")

        'END ADD CODE


        '*****************
        'BEGIN SEND CHANGES TO SQL SERVER

        Dim objCommandBuilder As New SqlCommandBuilder(da)
        da.Update(ds, "DH51")

        '07979 906888
        MsgBox("SQL Server updated successfully" & Chr(13) & "Check Server explorer to see changes")

        ' END SEND CHANGES TO SQL SERVER

Catch ex as Exception
        messagebox.show(ex.message)
End Try
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.