Welcome to Dream.In.Code
Become an Expert!

Join 150,413 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,019 people online right now. Registration is fast and FREE... Join Now!




What is wrong with this code :(

 
Reply to this topicStart new topic

What is wrong with this code :(

Najla
2 Apr, 2008 - 09:54 AM
Post #1

New D.I.C Head
*

Joined: 25 Mar, 2008
Posts: 10

hi..
I am building a website (digital repository for learning objects)with Microsoft visual studio 2005/ vb.net and sql2005

I used the following code which allows the user to create his own personal collection of learning objects
(the user enters the name of the personal collectionin atext box and clicks on create)
then the table of personal collection shold be changed to include the user inputs.
CODE


Protected Sub CreatePC_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreatePC.Click

        Dim myConnection As SqlConnection
        Dim myTransaction As SqlTransaction = Nothing


        Dim cmd As String = "INSERT INTO PersonalCollection(PCID,PCName,AccID) Values (@PCID,@PCName,@AccID)"

        Try

            myConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString1").ToString())

            myConnection.Open()

            myTransaction = myConnection.BeginTransaction()

            Dim myCommand As SqlCommand = New SqlCommand(cmd, myConnection, myTransaction)
            myCommand.Parameters.AddWithValue("PCID", 4)
            myCommand.Parameters.AddWithValue("PCName", PCName.Text)
            myCommand.Parameters.AddWithValue("AccID", 53)
            myCommand.ExecuteNonQuery()

        Catch ex As Exception
            If (myTransaction.Equals(Nothing) = False) Then
                myTransaction.Rollback()
            End If
            myTransaction.Commit()
        Finally
            myConnection.Dispose()

        End Try
    End Sub


but unfortunatly an error appears for the line:
If (myTransaction.Equals(Nothing) = False) Then
the error:"NullReferenceException was unhandled by user code"
"Object reference not set to an instance of an object"

help please sad.gif
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: What Is Wrong With This Code :(
2 Apr, 2008 - 10:59 AM
Post #2

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Your first issue is when you declare your SqlTransaction Object you immediately set it to nothing


vb

Dim myTransaction As SqlTransaction = Nothing



So when you try and reference it it doesn't exist. Try the following changes I made to your code


vb

Protected Sub CreatePC_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreatePC.Click
'Create and open our SqlConnection
Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString1").ToString())
'Open the connection
myConnection.Open()
'Generate our query
Dim cmd As String = "INSERT INTO PersonalCollection(PCID,PCName,AccID) Values (@PCID,@PCName,@AccID)"
'Create a command
Dim myCommand As SqlCommand = myConnection .CreateCommand()
'Declare our SqlTransaction Object
Dim myTransaction As SqlTransaction
'Start a local transaction
myTransaction = myConnection.BeginTransaction("CreatePC_Transaction")

' Must assign both transaction object and connection
' to Command object for a pending local transaction.
myCommand.Connection = myConnection
myCommand.Transaction = myTransaction

Try
'Set the properties of our SqlCommand
myCommand.CommandText = cmd 'What is it executing
myCommand.CommandType = CommandType.Text 'What kind of query are we executing
'Add our Parameters
myCommand.Parameters.AddWithValue("PCID", 4)
myCommand.Parameters.AddWithValue("PCName", PCName.Text)
myCommand.Parameters.AddWithValue("AccID", 53)
'Execute the query
myCommand.ExecuteNonQuery()
'Attempt to commit our Transaction
myTransaction.Commit()
Catch ex As Exception
'An Exception occurred so we need to
'roll the transaction back
myTransaction.Rollback()
Finally
'Close our connection now
myConnection.Dispose()
End Try
End Using
End Sub

User is offlineProfile CardPM
+Quote Post

Najla
RE: What Is Wrong With This Code :(
2 Apr, 2008 - 11:16 AM
Post #3

New D.I.C Head
*

Joined: 25 Mar, 2008
Posts: 10

PsychoCoder
thanks very much for your fast reply
I tried your code but the same error appeaes but with the line:
CODE

Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString1").ToString())

if you have any idea about what causes this error please help me
thanks agian

This post has been edited by Najla: 2 Apr, 2008 - 11:22 AM
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: What Is Wrong With This Code :(
2 Apr, 2008 - 11:22 AM
Post #4

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Change the line with the error to


vb

Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString1").ConnectionString



Also, show how you have your connection string in your web.config file if you can
User is offlineProfile CardPM
+Quote Post

Najla
RE: What Is Wrong With This Code :(
2 Apr, 2008 - 11:35 AM
Post #5

New D.I.C Head
*

Joined: 25 Mar, 2008
Posts: 10

PsychoCoder
I hope that my questions are not bothering you.,,,
the same error appears with the same line after your changes..
this is my web.config

CODE

<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.

            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
        -->
        <roleManager enabled="true" />
  <compilation debug="true" strict="false" explicit="true"/>
        <pages>
            <namespaces>
                <clear/>
                <add namespace="System"/>
                <add namespace="System.Collections"/>
                <add namespace="System.Collections.Specialized"/>
                <add namespace="System.Configuration"/>
                <add namespace="System.Text"/>
                <add namespace="System.Text.RegularExpressions"/>
                <add namespace="System.Web"/>
                <add namespace="System.Web.Caching"/>
                <add namespace="System.Web.SessionState"/>
                <add namespace="System.Web.Security"/>
                <add namespace="System.Web.Profile"/>
                <add namespace="System.Web.UI"/>
                <add namespace="System.Web.UI.WebControls"/>
                <add namespace="System.Web.UI.WebControls.WebParts"/>
                <add namespace="System.Web.UI.HtmlControls"/>
            </namespaces>
        </pages>
        <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
        <authentication mode="Forms" />
        <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
</configuration>



This post has been edited by Najla: 2 Apr, 2008 - 11:36 AM
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: What Is Wrong With This Code :(
2 Apr, 2008 - 01:14 PM
Post #6

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Well we now know why you're getting this error. You don't have a connection string in your web.config file. You wil notice at the top of your web.config a section dedicated to connection string (<connectionStrings/>, that is where you connection string must go. It must be like this


CODE

< connectionStrings>
    <add name="YourConnectionName"
   connectionString="Persist Security Info=False;
   Data Source=YourDatabase;
   Initial Catalog=YourTable;
   Integrated Security=SSPI;
   Trusted_Connection=TRUE;
   Application Name=SampleVBNetApplication"
   providerName="System.Data.SqlClient" />
  </ connectionStrings>


Just replace the items that begin with Your with your information, like your database name, your table, password, username, etc.
User is offlineProfile CardPM
+Quote Post

Najla
RE: What Is Wrong With This Code :(
3 Apr, 2008 - 02:35 AM
Post #7

New D.I.C Head
*

Joined: 25 Mar, 2008
Posts: 10

PsychoCoder
thank you very much
it works now smile.gif
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: What Is Wrong With This Code :(
3 Apr, 2008 - 02:59 AM
Post #8

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,483



Thanked: 161 times
Dream Kudos: 9075
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
No problem, glad I could help smile.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 07:59PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month