pratt
pratt

Reputation: 47

'condition is expected' in query

SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Projects\\csharp\\Login1\\App_Data\\Login.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
SqlDataReader dr;   

protected void  LinkButton1_Click(object sender, EventArgs e)
{
 conn.Open();
 cmd=new SqlCommand("Select * from LoginTable where User Name='"+TextBox1.Text+"'",conn);
 dr=cmd.ExecuteReader();   //  <---error here

 if(dr.Read())
 {
   Label1.Text="User name already exist";
   this.Label1.ForeColor=Color.Red;
 }
 else
 {
   Label1.Text="Name available";
 }
}

It shows the following error near dr=cmd.ExecuteReader();:

An expression of non-boolean type specified in a context where a condition is expected, near 'Name'.

Whats happening here

Upvotes: 2

Views: 164

Answers (6)

user2404823
user2404823

Reputation:

The user name must be specified as [User Name] or UserName so please check column name once

and also check for reserved keywords if you use them as column names please kept in square brasses [ ]

cmd=new SqlCommand("Select * from LoginTable where [User Name] = @userName",conn);
cmd.Parameters.AddWithValue("@userName", TextBox1.Text);

OR

cmd=new SqlCommand("Select * from LoginTable where UserName = @userName",conn);
cmd.Parameters.AddWithValue("@userName", TextBox1.Text);

Upvotes: 2

Ashraf Sabry
Ashraf Sabry

Reputation: 3182

Aside from the possible typo in the field name (UserName?), this is not how it should be done. Try this:

cmd = new SqlCommand("IF EXISTS(SELECT 1 FROM LoginTable where [User Name]=@p)" +
"SELECT 1 ELSE SELECT 0", conn);
cmd.Parameters.AddWithValue("@p", TextBox1.Text);

if(Convert.ToBoolean(cmd.ExecuteScalar()))
{
   Label1.Text="User name already exist";
   this.Label1.ForeColor=Color.Red;
}
else
   Label1.Text="Name available";

Upvotes: 2

Taj
Taj

Reputation: 1728

You should not give space between UserName in this statement:

cmd=new SqlCommand("Select * from LoginTable where **User Name** = '"+TextBox1.Text+"'", conn);

Upvotes: 2

zkanoca
zkanoca

Reputation: 9918

User Name consists of two words. And also use parameterized query.

cmd=new SqlCommand("Select * from LoginTable where [User Name]=@userName",conn);
cmd.Parameters.AddWithValue("@userName", TextBox1.Text);

Upvotes: 2

Randhi Rupesh
Randhi Rupesh

Reputation: 15060

The user name must be specified as [User Name] or UserName so please check column name once

Upvotes: 3

Jahan Zinedine
Jahan Zinedine

Reputation: 14864

Replace the User Name in where clause with [User Name]

Upvotes: 5

Related Questions