Reputation: 47
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
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
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
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
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
Reputation: 15060
The user name must be specified as [User Name] or UserName so please check column name once
Upvotes: 3