Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Error:System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '('. Must declare the scalar variable "@Username". at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Registration.Button1_Click(Object sender, EventArgs e) in C:\Users\rache\source\repos\Registration Page\Registration.aspx.cs:line 54 ClientConnectionId:64f25c63-907a-4f1e-bd7c-53672cc7b7b1 Error Number:102,State:1,Class:15

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ValidationSettings.UnobtrusiveValidationMode= UnobtrusiveValidationMode.None;
        if(IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            conn.Open();
            string checkuser = "select count(*) from [UserData] where Username='" + TextBoxUN.Text +"'";
            SqlCommand com= new SqlCommand(checkuser, conn);
            int temp = Convert.ToInt32(com.ExecuteScalar().ToString());   
            if (temp ==1)
            {
                Response.Write("User already Exits");

            }
            conn.Close();
        }
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {

    }

    protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            conn.Open();
            
            string insertQuery = "insert into UserData (Username, Email,Password,Country) values (@Username,@email,@password,@country)";
            SqlCommand com = new SqlCommand(insertQuery, conn);
            com.Parameters.AddWithValue("(@Username", TextBoxUN.Text);
            com.Parameters.AddWithValue("(@email", TextBoxEmail.Text);
            com.Parameters.AddWithValue("(@password", TextBoxPass.Text);
            com.Parameters.AddWithValue("(@country",DropDownListCountry.SelectedItem.ToString());
            
            com.ExecuteNonQuery();
            Response.Redirect("Manager.aspx");
            Response.Write("Registration is successful");

            conn.Close();
        }
        catch(Exception ex)
        {
            Response.Write("Error:" +ex.ToString());
        }
    }

}
Posted
Updated 13-Jun-22 3:47am
v2

So little code, so many errors ...
Let's start with the most serious ones:
1) Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

2) Never store passwords in clear text - it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]

And remember: if this is web based and you have any European Union users then GDPR applies and that means you need to handle passwords as sensitive data and store them in a safe and secure manner. Text is neither of those and the fines can be .... um ... outstanding. In December 2018 a German company received a relatively low fine of €20,000 for just that.

Now the less serious ...
Why are you taking a numeric value, converting it to a string, then convertit it back to a number again?
C#
string checkuser = "select count(*) from [UserData] ...
...
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
Just cast it!
C#
string checkuser = "select count(*) from [UserData] ...
...
int temp = (int) com.ExecuteScalar();


Fix all of that throughout your whole code, and the problem you have noticed will almost certainly go away at the same time ...
 
Share this answer
 
Comments
Richel Debalucos 15-Jun-22 9:48am    
thank you:)
OriginalGriff 15-Jun-22 9:56am    
You're welcome!
C#
com.Parameters.AddWithValue("(@Username", TextBoxUN.Text);
//                           ^ are sure about the '(' here ?
 
Share this answer
 
Comments
Richel Debalucos 15-Jun-22 9:47am    
thank you that's the reason why my code is error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900