This is my search button on MasterPage.master
<asp:TextBox ID="Search" style="width:339px ; height: 20px;" runat="server" placeholder="Search Woooo" class="textbox" formnovalidate="formnovalidate"></asp:TextBox>
<asp:ImageButton ID="ImageButtonSearch" runat="server" ImageUrl="~/Images/Icons/search.png" Width="22px" OnClick="ImageButtonSearch_Click" CausesValidation="False" />
MasterPage.master.cs
protected void ImageButtonSearch_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("~/search.aspx?Search=" + Search.Value);
}
search.aspx.cs
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;
public partial class Default2 : System.Web.UI.Page
{
string cs = Global.CS;
protected void Page_Load(object sender, EventArgs e)
{
string search = Request.QueryString["search"];
if (!Page.IsPostBack)
{
string xx = "";
string sql = @"SELECT studentID FROM Student WHERE username == '"+ search + "'";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
xx += string.Format("{0}",dr["sudentID"]);
}
dr.Close();
con.Close();
test.InnerHtml = xx;
}
}
}
I wanna try search based on username on the search box. But after i clicked on search button, it display Incorrect syntax near '='. Source error: dr = cmd.ExecuteReader();. I already search the problem through many places but i still can't understand. I'm still new at c#
You are mixing SQL with C#. Equality comparison is done with a single =
.
More importantly, you are vulnerable to SQL injection. You should take care of this first.
The SQL should look like this:
SELECT studentID FROM Student WHERE username = @username
And you should add the parameter @username
to your C# code, like this:
cmd.Parameters.Add("@username").Value = search;
The issue is that in T-SQL a SINGLE equal sign is required: @"SELECT studentID FROM Student WHERE username = '"+ search + "'";
(next to username =
)
UPD As Patrick Hofman points out above, you might want to research SQL injection and common ways to protect against it: https://msdn.microsoft.com/en-us/library/ff648339.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.