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?
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;
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.
please change as below..
dt.DefaultView.RowFilter ="Forename LIKE '%" + SearchFor + "%'"
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.