Must declare the scalar variable “@ID”

Problem

In an ASP.NET Application, you are using ListView, you are trying to delete a record. Update, Insert everything works fine but delete does not work. The SQL syntax is correct

[csharp]
DeleteCommand=”delete from SalesRep where ID = @ID”

[/csharp]

You are using Eval or Bind with your parameter like this

[csharp]

or

[/Csharp]

Your ListView is declared like this

[csharp]

[/csharp]

Error Message:

The error is coming from SQL not ASP.NET
Must declare the scalar variable “@ID”.

You will find that although the error is coming from SQL but the cause is ASP.NET ListView.

Why is this error?

First of all it is interesting to knote that this error is not comming from ASP.NET or C# code. This is comming from SQL. you can verify this by reading the actual exception. It will say SQL Exception. The problem here is that someone the @ID is not properly updated and blinded into the delete query, that causes this exception.

Solution

Solution in this case is really simple. Include DataKeyNames=”ID” parameter in your ListView declaration. That should address the problem. It is funny at the end of the day, the error seems to be in ASP.NET not SQL while we know the exception is certainly from SQL.

[csharp]

[/csharp]

Also note that you do not need to bind the ID field in your ASP.NET Code or even use Eval(“ID”). ID must simply exist in the select query. There is not need to display it in the ListView to make it work.

If it still does not solve your problem please let me know.

Advertisements
This entry was posted in Troubeleshoot and tagged . Bookmark the permalink.

3 Responses to Must declare the scalar variable “@ID”

  1. ali says:

    <asp:SqlDataSource ID="SqlDataSource2" runat="server"
    ConnectionString="”
    SelectCommand=”SELECT * FROM [registration]”
    UpdateCommand=”Update[registration] Set [UserName]=@UserName, [Phone]=@Phone, [Address]=@Address, [Email]=@Email, [Gender]=@Gender, [Password]=@Password where [FormNumber]=@FormNumber”
    DeleteCommand=”DELETE FROM [registration] where [FormNumber]=@FormNumber”
    ProviderName=””>

    i have same issue with gridview i.e. Must declare the scalar variable “@FormNumber”

    • admin says:

      Did you add the following property to your GridView

      DataKeyNames=”FormNumber”

      Where FormNumber is your primary key to the record.

  2. WA says:

    YEAH THANKS A LOT ITS NOT WORKING 🙂

Leave a Reply to ali Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s