Click here to Skip to main content
14,691,021 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Server Error in '/' Application.

An expression of non-boolean type specified in a context where a condition is expected, near 'Name'.
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: An expression of non-boolean type specified in a context where a condition is expected, near 'Name'.

What I have tried:

Source Error:


Line 19: String checkuser = "select count(*) from UserData where User Name=' " + TextBoxUN.Text + "'";
Line 20: SqlCommand com = new SqlCommand(checkuser, conn);
Line 21: int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
Line 22: if (temp == 1)
Line 23: {
Posted
Updated 8-Sep-20 0:58am

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

Beyond that, you have a space in your column name. You need to properly quote the column name for the query to work.
const string checkuser = "select count(*) from UserData where [User Name] = @UserName";
using (SqlConnection connection = new SqlConnection("..."))
using (SqlCommand command = new SqlCommand(checkuser, connection))
{
    command.Parameters.AddWithValue("@UserName", TextBoxUN.Text);
    
    connection.Open();
    object result = command.ExecuteScalar();
    
    int temp = (result == null || Convert.IsDBNull(result)) ? 0 : Convert.ToInt32(result);
    if (temp != 0)
    {
        ...
    }
}
Ideally you should update your database so that you don't use "special" characters or whitespace in any table or column names.
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
   
2 things:
First off, bad way of getting data from database. Totally open for security threat via SQL Injection.
Read about protecting from SQL Injection here: SQL Injection Mitigation: Using Parameterized Queries[^]

Second,
believe 'User Name' s the coumn name with space in your database. If so, put that in square brackets:
String checkuser = "select count(*) from UserData where [User Name]=' " + TextBoxUN.Text + "'";

Currently, User name is not considered one word by SQL and throws back an 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