Syntax error: Missing operand after 'Student&#

2019-12-16 19:55发布

This is the code I have:

private void btnSearch_Click(object sender, RoutedEventArgs e)
{

        using (SqlConnection sc = new SqlConnection(sConn))
        {
            sc.Open();


            string SearchFor = txtSearch.Text;



            using (SqlDataAdapter adapter = new SqlDataAdapter())
            {
                DataTable dt = new DataTable();
                grdData.ItemsSource = dt.DefaultView.RowFilter = string.Concat("SELECT * FROM Student WHERE Forename LIKE '%", SearchFor, "%'");
            }

When I run the code I get:

"Syntax error: Missing operand after 'Student' operator."

I'm using WPF... I want it so I can search for people by just typing a letter of their name what can I do?

4条回答
对你真心纯属浪费
2楼-- · 2019-12-16 20:27

You need to fill your DataTable first with some data and then you can filter results

using (SqlConnection sc = new SqlConnection(sConn))
{
   sc.Open();
   using (SqlDataAdapter adapter = new SqlDataAdapter())
   {
       adapter.SelectCommand = new SqlCommand("SELECT * FROM Student", sc);
       var dataset = new DataSet();
       adapter.Fill(dataset);
       var dt = dataset.Tables[0];
       var dv = dt.DefaultView;
       dv.RowFilter = String.Concat("[Forename] LIKE '%", SearchFor, "%'");
       grdData.ItemsSource = dv;
   }
}

or filter in SQL without RowFilter

var cmd = new SqlCommand("SELECT * FROM Student WHERE Forename LIKE @forename", sc);
cmd.Parameters.AddWithValue("@forename", String.Concat("%", SearchFor, "%"));
adapter.SelectCommand = cmd;
查看更多
地球回转人心会变
3楼-- · 2019-12-16 20:29

In your filter, you only need to specify the WHERE clause, it's not a full SQL SELECT statement that is needed. So it should look like this:

grdData.ItemsSource = dt.DefaultView.RowFilter = string.Concat("Forename LIKE '%", SearchFor, "%'");

Be aware though, that a user could enter some characters like %, ' etc.

查看更多
祖国的老花朵
4楼-- · 2019-12-16 20:40

please change as below..

dt.DefaultView.RowFilter ="Forename LIKE '%" + SearchFor + "%'"
查看更多
The star\"
5楼-- · 2019-12-16 20:45

The "RowFilter" query is not a complete SQL query but rather a subset of a SQL query. In your case you want something like:

grdData.ItemsSource = dt.DefaultView.RowFilter = String.Format("[Forename] LIKE '%{0}%'", SearchFor);

For future reference: MSDN Documentation.

查看更多
登录 后发表回答