Click here to Skip to main content
15,895,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Line 18: string checkuser = "select(*)from Table where [UserName] = '"+TextBoxUsername.Text+ "'";
Line 19: SqlCommand com = new SqlCommand(checkuser, conn);
Line 20: int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
Line 21: if(temp == 1)
Line 22: {

Hello folks, I have encountered this error which says "An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near '*'. " and its pointing towards Line 20.

I'm a beginner ,trying to learn Asp.net. Please help me out if anyone has a solution.
P.S : i also saw the other guy has same error, and i tried to change the code,but still have the same problem. Thanks in advance

What I have tried:

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)
{

if(IsPostBack){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select(*)from Table where [UserName] = '"+TextBoxUsername.Text+ "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if(temp == 1)
{
Response.Write("User already exists");
}

conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try{


SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table (UserName,Email,Password,Country) values (@Uname,@email,@password,@country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("@Uname", TextBoxUsername.Text);
com.Parameters.AddWithValue("@email", TextBoxEmailid.Text);
com.Parameters.AddWithValue("@password", TextBoxpassword.Text);
com.Parameters.AddWithValue("@country", DropDownListCountries.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 28-Dec-16 10:08am
Comments
Afzaal Ahmad Zeeshan 28-Dec-16 14:19pm    
You are still not focusing on writing SQL queries, you are still using Table as the table name. Consider learning how to write SQL queries.
Subhoj Kumar 28-Dec-16 14:22pm    
Do you think that's where the problem is?

Probably, it the name of your database table: TABLE is an SQL reserved word and that is probably confusing the SQL command parser.
The best solution is: don't call your table "Table" as it's not a descriptive name for what it contains. Call it "Students", or "Customers", or "Users".
The worst solution is: surround the reserved word with square brackets: SELECT * FROM [Table] instead of SELECT * FROM Table

But ... Don;t do it like that! 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. Use Parametrized queries instead. This is absolutely critical when you are looking at registration or login pages as concatenation allows non-logged in users full control of your database ...
 
Share this answer
 
Comments
Subhoj Kumar 28-Dec-16 14:37pm    
i updated my table name to UserData. Now there is a new error "Object reference not set to an instance of an object." pointing out to this line
"int temp = Convert.ToInt32(com.ExecuteScalar().ToString()); "
Michael_Davies 28-Dec-16 15:17pm    
You are selecting everything from the row identified by the user, executescalar expects only to return one item, change the * to the field you want from the row.

Also if the returned field is an integer why convert it to string to convert it back to integer?

Perhaps you meant to use COUNT(*) as you test the return for the value 1.
Try this:

string checkuser = "select COUNT(*) from [Table] where [UserName] = '"+TextBoxUsername.Text+ "'";

SqlCommand com = new SqlCommand(checkuser, conn);

if (Convert.ToInt32(com.ExecuteScalar()) == 1)
{...
 
Share this answer
 
v3
Comments
Subhoj Kumar 28-Dec-16 16:13pm    
Error 1 Operator '==' cannot be applied to operands of type 'object' and 'int' C:\Users\LENOVO\Documents\Visual Studio 2013\WebSites\LoginPage\Registration.aspx.cs 22 16 LoginPage
is the error when i tried that
Michael_Davies 28-Dec-16 16:15pm    
Updated solution.
Subhoj Kumar 28-Dec-16 16:29pm    
Error :System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'ID', table 'C:\USERS\LENOVO\DOCUMENTS\VISUAL STUDIO 2013\WEBSITES\LOGINPAGE\APP_DATA\REGISTRATION.MDF.dbo.UserData'; column does not allow nulls. INSERT fails. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.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) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Registration.Button1_Click(Object sender, EventArgs e) in c:\Users\LENOVO\Documents\Visual Studio 2013\WebSites\LoginPage\Registration.aspx.cs:line 43 ClientConnectionId:f92c5277-f1ec-4b86-9045-bd4dddc1de3a

even though i kept the option of not allowing nulls in my column "ID" still shows this
Michael_Davies 28-Dec-16 16:32pm    
I take it that is the INSERT that follows the check for exists.

Do you have and ID field and is it auto numbered, if so try putting DEFAULT in the value position for the auto field:

string insertQuery = "insert into Table (ID,UserName,Email,Password,Country) values (DEFAULT,@Uname,@email,@password,@country)";

For further help show the table schema.
Subhoj Kumar 28-Dec-16 16:43pm    
CREATE TABLE [dbo].[UserData] (
[ID] INT NOT NULL,
[UserName] NCHAR (40) NULL,
[Email] NCHAR (40) NULL,
[Password] NCHAR (20) NULL,
[Country] NCHAR (20) NULL
);

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