variable not a variable

Error:
Must declare the variable '@cartDateTime'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Must declare the variable '@cartDateTime'.

Dim connStr As SqlConnection
            Dim cmdInsert As SqlCommand
            Dim strInsert As String
            Dim dtmDate As DateTime
            dtmDate = DateTime.Now()
            connStr = New SqlConnection(ConfigurationSettings.AppSettings("sqlCon.ConnectionString"))
            strInsert = "INSERT Carts ( cartDateTime ) VALUES ( @cartDateTime )"
            cmdInsert = New SqlCommand(strInsert, connStr)
            cmdInsert.Parameters.Add("@cartDateTime", dtmDate)
            connStr.Open()
            cmdInsert.ExecuteNonQuery()
            connStr.Close()

0
lrsd
2/16/2006 3:47:01 PM
asp.net.object-datasource 16182 articles. 0 followers. Follow

10 Replies
1312 Views

Similar Articles

[PageSpeed] 35

Try the following:

Dim connStr As SqlConnection
Dim cmdInsert As SqlCommand
Dim strInsert As String
Dim dtmDate As DateTime
dtmDate = DateTime.Now()
connStr = New SqlConnection(ConfigurationSettings.AppSettings("sqlCon.ConnectionString"))
strInsert = "INSERT Carts ( cartDateTime ) VALUES ( @cartDateTime )"
cmdInsert = New SqlCommand(strInsert, connStr)
cmdInsert.Parameters.Add("@cartDateTime", dtmDate)
cmdInsert.Prepare()
connStr.Open()
cmdInsert.ExecuteNonQuery()
connStr.Close()

HTH,
Ryan


Ryan Olshan
ASPInsider | Microsoft MVP, ASP.NET
http://ryanolshan.com

How to ask a question
0
StrongTypes
2/16/2006 6:13:54 PM

I feel like I'm getting close now.

SqlCommand.Prepare method requires all parameters to have an explicitly set type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: SqlCommand.Prepare method requires all parameters to have an explicitly set type.
Source Error:
Line 287:            cmdInsert.Parameters.Add("@cartDateTime", dtmDate.Date)
Line 288:            connStr.Open()
Line 289:            cmdInsert.Prepare()
Line 290:            cmdInsert.ExecuteNonQuery()
Line 291:            connStr.Close()

BTW... I fixed my pager; it works great now.

0
lrsd
2/16/2006 6:34:10 PM
You need to define a datatype for your parameter. I would explicitly
define the parameter, define its datatype, assign it's value and add it
to my command object's parameter collection.

dim param as SqlParameter = new SQLParameter("@cartDateTime",SqlDbType.DateTime)
param.Value = dtmDate
cmdInsert.Parameters.Add(param)

Good Luck

0
pcdanno
2/16/2006 6:41:01 PM

myCommand.Parameters.Add(New SqlParameter("@cartDateTime",SqlDbType.datetime)).value = dtmDate

***********************
Dinakar Nethi
Life is short. Enjoy it.
***********************
0
ndinakar
2/16/2006 6:41:35 PM

SqlParameter p = new SqlParameter("@cartDateTime", SqlDbType.DateTime, 8)
p.Value = dtmDate.Date
cmdInsert.Parameters.Add(p)

HTH,
Ryan


Ryan Olshan
ASPInsider | Microsoft MVP, ASP.NET
http://ryanolshan.com

How to ask a question
0
StrongTypes
2/16/2006 6:42:42 PM

Thanks you all for the input.
All suggestions gave me the same error:

Must declare the variable '@cartDateTime'.

I'm throwing my laptop out the window and I'm going to buy a typewriter.

0
lrsd
2/16/2006 6:56:39 PM

You know there's a funny part to this. It's actually inserting the dtmDate in the database.

I just checked and it's there: 2/16/2006 1:06:00 PM

0
lrsd
2/16/2006 7:07:26 PM

Something is happening when I try to use the 'cartID' that I'm creating by inserting the 'cartDateTime'. It's still giving me this: Must declare the variable '@cartDateTime'. 
I am creating a record, but I can't use it. Here's what I'm doing...


Private Sub btnAddToCart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddToCart.Click
        If Request.QueryString("CartID") = "" Then
            'create cartID
            Dim connStr As SqlConnection
            Dim cmdInsert As SqlCommand
            Dim strInsert As String
            Dim dtmDate As DateTime
            dtmDate = DateTime.Now()
            connStr = New SqlConnection(ConfigurationSettings.AppSettings("sqlCon.ConnectionString"))
            strInsert = "INSERT Carts ( cartDateTime ) VALUES ( @cartDateTime )"
            cmdInsert = New SqlCommand(strInsert, connStr)
            Dim paramDate As SqlParameter
            paramDate = New SqlParameter("@cartDateTime", SqlDbType.DateTime.DateTime)
            paramDate.Value = dtmDate.Date()
            connStr.Open()
            cmdInsert.Parameters.Add(paramDate)
            cmdInsert.ExecuteNonQuery()
            connStr.Close()
            'get max customerID
            Dim connStr2 As SqlConnection
            Dim sqlSelect As String
            Dim sqlCmdSelect As SqlCommand
            Dim sdReader5 As SqlDataReader
            connStr2 = New SqlConnection(ConfigurationSettings.AppSettings("sqlCon.ConnectionString"))
            sqlSelect = ("SELECT MAX(customerID) AS MXcID FROM Carts")
            sqlCmdSelect = New SqlCommand(sqlSelect, connStr2)
            connStr2.Open()
            sdReader5 = sqlCmdSelect.ExecuteReader(CommandBehavior.CloseConnection)
            If sdReader5.Read() Then
                Dim connStr3 As SqlConnection
                Dim sqlSelect2 As String
                Dim sqlCmdSelect2 As SqlCommand
                Dim sdReader6 As SqlDataReader
                connStr3 = New SqlConnection(ConfigurationSettings.AppSettings("sqlCon.ConnectionString"))
                sqlSelect2 = ("SELECT cartID FROM Carts WHERE customerID = '" & sdReader5("MXcID") & "'")
                sqlCmdSelect2 = New SqlCommand(sqlSelect2, connStr3)
                connStr3.Open()
                sdReader6 = sqlCmdSelect2.ExecuteReader(CommandBehavior.CloseConnection)
                If sdReader6.Read() Then
                    Dim connStr4 As SqlConnection
                    Dim cmdInsert2 As SqlCommand
                    Dim strInsert2 As String
                    connStr4 = New SqlConnection(ConfigurationSettings.AppSettings("sqlCon.ConnectionString"))
                    strInsert2 = "INSERT CartItems ( cartID, customerID, item1ID, quantity, pounds, regDec, grWb, flavor, item2ID, item2regDec, item2grWb, item2flavor, item3ID, item3regDec, item3grWb, item3flavor ) VALUES ( @cartID, @customerID, @item1ID, @quantity, @pounds, @regDec, @grWb, @flavor, @item2ID, @item2regDec, @item2grWb, @item2flavor, @item3ID, @item3regDec, @item3grWb, @item3flavor )"
                    cmdInsert2 = New SqlCommand(strInsert, connStr4)
                    connStr4.Open()
                    cmdInsert2.Parameters.Add("@cartID", sdReader6("cartID"))
                    cmdInsert2.Parameters.Add("@customerID", sdReader5("MXcID"))
                    cmdInsert2.Parameters.Add("@item1ID", 156432)
                    If Me.ddlQuantity.Enabled = True Then
                        cmdInsert2.Parameters.Add("@quantity", ddlQuantity.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@quantity", 0)
                    End If
                    If Me.ddlPounds.Enabled = True Then
                        cmdInsert2.Parameters.Add("@pounds", ddlPounds.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@pounds", 0)
                    End If
                    If Me.ddlRegDec.Enabled = True Then
                        cmdInsert2.Parameters.Add("@regDec", ddlRegDec.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@regDec", 0)
                    End If
                    If Me.ddlPackaged.Enabled = True Then
                        cmdInsert2.Parameters.Add("@grWb", ddlPackaged.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@grWb", 0)
                    End If
                    If Me.ddlFlavors.Enabled = True Then
                        cmdInsert2.Parameters.Add("@flavor", ddlFlavors.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@flavor", 0)
                    End If
                    If Me.ddlItem2.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item2ID", ddlItem2.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item2ID", 0)
                    End If
                    If Me.ddlItem2RegDec.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item2RegDec", ddlItem2RegDec.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item2RegDec", 0)
                    End If
                    If Me.ddlItem2Packaged.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item2grWb", ddlItem2Packaged.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item2grWb", 0)
                    End If
                    If Me.ddlItem2Flavors.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item2flavor", ddlItem2Flavors.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item2flavor", 0)
                    End If
                    If Me.ddlItem3.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item3ID", ddlItem3.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item3ID", 0)
                    End If
                    If Me.ddlItem3RegDec.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item3RegDec", ddlItem3RegDec.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item3RegDec", 0)
                    End If
                    If Me.ddlItem3Packaged.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item3GrWb", ddlItem3Packaged.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item3GrWb", 0)
                    End If
                    If Me.ddlItem3Flavors.Enabled = True Then
                        cmdInsert2.Parameters.Add("@item3Flavors", ddlItem3Flavors.SelectedValue)
                    Else
                        cmdInsert2.Parameters.Add("@item3Flavors", 0)
                    End If
                    cmdInsert2.ExecuteNonQuery()
                    If Request.QueryString("CartID") = True Then
                        'something else here
                    End If
                End If
            End If
        End If
    End Sub

0
lrsd
2/16/2006 9:04:14 PM
I see in your code you are making a lot of trips to the DB. Why dont you consolidate all your stuff in one trip by writing a stored procedure.
Create a proc and pass all the values related to Cart and CartItems.
Do the insert into Cart, get the id using SCOPE_IDENTITY().
Then do the INSERT into CartITems again.
 
The way you are doing it now may work but the MAX(customerID) may not always return accurate value. IF you have multiple connections the ID could get swapped. Doing it all in a stored proc not only reduces your server trips but also can guarantee you a more accurate value of the id just inserted.
 
Finally, in your code you have
 
paramDate = New SqlParameter("@cartDateTime", SqlDbType.DateTime.DateTime)
 
You have DateTime twice in there in "SqlDbType.DateTime.DateTime". Is that a typo? If not that could be the cause of your error.

***********************
Dinakar Nethi
Life is short. Enjoy it.
***********************
0
ndinakar
2/16/2006 9:38:06 PM
Thanks, I'll try the stored procedure route. I wrote my first one this morning and it worked pretty well. It was a typo, and I still got the error after I fixed it. Thanks again.
0
lrsd
2/16/2006 9:52:38 PM
Reply:

Similar Artilces:

Variable Variables
Hi, Maybe the solution is very simple, but how do I create variable variables in vb.net? I want to use the value of a variable as a part of the name of another variable. A very simple example below: code: Dim a As String a = "1" Label a.Text = "hi" page: <asp:Label id="Label1" runat="server">Label</asp:Label> In need this to change a range of values by using just one loop. I can´t do that without creating a variable variable name. Hi, check out this little demo application I created for you: ...

variable of variables
Say I have 2 scenarios and I want to use a different variable depending on which scenario applies without coding this logic. So I could have a database table t_variables which has: Scenario: Variable: --------- -------- 1 v_name 2 v_company In my Powerbuilder code I'd have values in v_name & v_company. What I'd like to be able to do is to select which variable to use from the table and assign that to something, e.g. select variable into v_variable from t_variables where scenario = 1 so at this point v_variable would be 'v_name'...

variable variables?
Hello! How to make a variable receive an increment in the name? I want to do it for example: I have: Label1->Caption = "1"; Label2->Caption = "2"; Label3->Caption = "3"; Label4->Caption = "4"; And I want to do something like that: for (i=1; i<5; i++) { Label+i->Caption = i; } Any idea? Can I do something like that? Thanks and regards Alexandre Create a vector of pointers to the various objects. In your case below, construct a vector (called Labels) of pointers to TLable long enough to hold pointers to...

.NET AJAX "Object variable or With block variable not set" Error
I am using the Timer control in the ASP.NET AJAX 1.1 Framework on my website.  I have run into one problem using it and need some help finding the bug fix or work around.  On the site my MasterPage is the page that acutally has the AJAX controls, and most of the content pages have UserControls.  When you first load one of these page everything seems to execute fine, but when the Timer control does a tick a few seconds later I get the following popup "Object variable or With block variable not set".  This error seems to happen when the DataBind() method is excute...

Creating variable/object from a variable?
Hi. Is there a way to dynamically create a variable in a function using another variable? I have a a number of objects, to be exact 27, that I want to do the exact same operation against, so I thought it would be efficient to place this operation inside a function, and then by calling the function and supply part of the object as a argument to that function. Something like this: --- CODE --- Function getObjectStatus(targetObject as string) return ("obj" & targetObject).Value End Function --- CODE --- Or something like that. Is this possible? When...

Object variable or With block variable not set.
Hi, I'm goofing around with an old program of my dad's written in VB (older vb) inside of an excel program. I want to make it web based utilizing a Datagrid instead of a spreadsheet. So far I'm able to take the data from a text file and load it into a datagrid. Now I need to use an array to tell certain data to go to certain rows and columns. I have two problems: First: I don't think I'm setting up the array right Second: It doesn't like the e.Item.Cells(n, 1) =.... Errors are noted in the code. Here is the code Public Class PPData Inherits System.Web.UI.Page ...

Object variable or With block variable not set
Dear sir I'm getting this error while trying to access an ASP.NET system on a Server. An user log on windows and can access the main page on ASP.NET system. Another user lon on windows and can't access the main page on ASP.NET System. Both are using the same machine. I tried again on another machine and I got error, that is: an user get access and another user doesn't get. Code (Error occurs on code bellow) txtReferencia.Attributes.Add("onkeyup", "ConvertToUpperCase(this)") 'text box If sErro.Equals(String.Empty) Then If Not IsPostBac...

Object variable or With block variable not set
Hi All, I have an ASP app running on win 2000 server.  I've copied the app over to an XP Pro sp3 for testing.  I've also copied and registered all of the app's dll's.  User authentication is done through .dll file.  As I've mentioned already, the app is runing without a problem but not the copy.  I keep getting the Object variable or with... error.  I don't have dll codes and I've ran out of ideas.  also, I've checked the permissions and they seem to be correct.  Any and all ideas will be greatly appreciated. Than...

Object variable or With block variable not set.
Hi I dont know what string to put this in but Im working on this web application a total rewrite of an classical ASP site into the world of ASP.NET 2.0 and now im going to send some information to a secure server as below: and I get the error Object variable or With block variable not set. Dim objHTTP As ObjectobjHTTP = Server.CreateObject("Microsoft.XMLHTTP")objHTTP.Open("GET", "https://securewebsite.com, False) 'Sending request objHTTP.Send()Dim strHTML = objHTTP.responseTextobjHTTP = Nothing 'Check for error in communication If Err.Nu...

Object variable or With block variable not set.
Session("DataTableOne").Rows.RemoveAt(0) I am getting an error  on the above  lineObject variable or With block variable not set. First, make sure that the "DataTableOne" has a value.. in your case I think it has no value when you access the code.. So add the follwong code to check if your session has a value If Not Session("DataTableOne") Is Nothing Then End If Second, you need to cast the object returned from the Session to the correct type before you can access the Rows.RemoveAt property and method. DirectCast(Session("DataTableOne"),DataTable).Rows.RemoveAt(0) The ...

Javascript variable to VB.Net Variable
Could someone please point me to a way to pass a string that is contained in a Javascript variable over to a Visual Basic.Net variable? If something already exists in the Forums I could not find it through the search. Thanks in advance, Welcome to the ASP.NET Forums, Haywire. The following article shows how you can pass Javascript information back to your server-side code: How postbacks work in ASP.NETAlister...

Object variable or With block variable not set #2
 What possible reasons are there for me getting this error?The error is happening when I do the following in my repeaters ItemDataBound sub:Dim AttachmentID as integer = e.item.dataitem("AttachmentID") Thanks for your help. Regards, Curt I assume you are trying to execute this code in your ItemDataBound event, am I right? It seems e.item.dataitem("AttachmentID") is invalid. This may be caused by the fact that your Repeater calls the ItemDataBound event also for the Header and Footer template. So you typically need to surround your data accessing code with a co...

Object variable or With block variable not set #3
I am converting classic asp page to an asp.net. The page uses an include file (topnav.asp) that must remain on the page. Inside the include file is the following code: If rsSwitch("Switch") =("-1") then%> <a href="http://www.mysite.comg/link1.asp">Link 1</a> <%else%><a href="http://www.mysite.comg/link2.asp">Link 2</a> <%end if%>  I am getting the error below and am not sure why?   Object variable or With block variable not set. Description: An unhandled exception occurred during the execution o...

Object variable or with block variable not set error
I have converted some ASP webpages to ASP.net using Migration Assistant.These pages has reference to some VB dlls and VC++ EXEs.The ASP.Net converted pages works well in my system without any problem. but...in the testing machine,we rebuild the package of VB and VC++ and there i tried to run this ASP.NET pages.but it is giving 'COMException:Object variable or with block variable not set' error in the line where we create instance to the VB dlls.Even i tried with tlbimp tool in that machine to create wrapper classes again in that machine.Still it is not working.No problem with registering of...

Web resources about - variable not a variable - asp.net.object-datasource

Variable - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Westpac interest rate rise is one of many variable loan rate rises
WESTPAC is not alone in hitting its owner-occupier customers with a surprise interest rate rise, as dozens of other variable rate home loans ...

Airbnb upgrades variable pricing tool for hosts
Online home rental group Airbnb is rolling out an upgraded variable pricing tool that automatically raises or cuts room rates based on supply ...

Commonwealth Bank raises variable home loan rates
Home owners' mortgage costs are set to rise by hundreds of dollars a year, after the Commonwealth Bank became the latest bank to hike interest ...

CBA lifts variable home loan rates to offset costs associated with stricter capital requirements
The Commonwealth Bank to lift its home loan interest rates independently of the Reserve Bank to partially offset costs associated with stricter ...

Washington Square Signs Spielbergs, Choi Joins Variable and More
... films and an episode of the HBO comedy series "Girls," on which he plays the role of Ray Ploshansky. New York-based creative collective Variable ...

YouTube v10.32 Tweaks Some Interface Elements And Includes Hints About Virtual Reality Content And Variable ...
Forget Update Wednesday! Monday is the new big day. Not only were we treated to the latest M preview release and the official Marshmallow name, ...

"You have to ignore many variables to think women are paid less than men. California is happy to try." ...
Writes Sarah Ketterer in The Wall Street Journal in "The ‘Wage Gap’ Myth That Won’t Die" (which you can get to without subscribing if you Google ...

Cisco Debuts Open Pay Variable Pricing, Updates CCRE
Cisco Debuts Open Pay Variable Pricing, Updates CCRE Channel Partners Kris Snow, president of Cisco Capital, says the company's new Open Pay ...

Expert Reveals the Latest Variable Capacity Technology
Learn about gForce Ultra CRAC equipment, the latest variable capacity technology to lower energy usage and increase reliability.

Resources last updated: 11/27/2015 3:35:42 AM