WPF -数据网格过滤器的名称与文本框

本文关键字:文本 过滤器 数据 数据网 网格 WPF | 更新日期: 2023-09-27 18:18:36

我用这个代码来过滤我的dataGrid与一个文本框,它的工作原理很好,通过Id过滤,但如果我把它改为按名称过滤(我只是改变"Id"在查询"名称"),它不起作用,像"列名"输入的文本"是无效的。当查询设置为Id并输入字母时,也会出现同样的错误,显然它只适用于数字。

代码如下:

private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
            try {
                SqlConnection con = new SqlConnection(@"Data Source =.'SQLEXPRESS; AttachDbFilename = C:'Users'Sione'Documents'AcademiaSQLDB.mdf; Integrated Security = True; Connect Timeout = 30; User Instance = True");
                con.Open();
                string query = "select * from instrutor";
                if (textBox.Text != "") // Note: txt_Search is the TextBox..
                {
                    query += " where Nome =" + textBox.Text;
                }
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.ExecuteNonQuery();
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable("instrutor");
                adp.Fill(dt);
                instrutorDataGrid.ItemsSource = dt.DefaultView;
                adp.Update(dt);
                con.Close();
            } catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
}

那么我如何通过名称过滤dataGrid呢?通过Id过滤工作完美,但它不是很用户友好。由于

WPF -数据网格过滤器的名称与文本框

您需要用'包装您的过滤器下面这行:

query += " where Nome =" + textBox.Text;
成为

query += " where Nome ='" + textBox.Text + "'";

请注意,这是一个快速修复,您需要考虑@Dennis回答

不要使用字符串连接来构建SQL查询,这会导致SQL注入。使用参数代替:

private SqlCommand CreateCommand(SqlConnection connection)
{
   return new SqlCommand("select * from instrutor", connection);
}
private SqlCommand CreateCommand(SqlConnection connection, TextBox textBox)
{
    var command = new SqlCommand("select * from instrutor where Nome = @nome",  
        connection);
    command.Parameters.AddWithValue("@nome", textBox.text);
    return command;
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
    // ...
    using (var command = !string.IsNullOrEmpty(textBox.Text) ? 
        CreateCommand(conn, textBox) : CreateCommand(conn))
    {
        // ...
    }
    // ...
}

还要注意:1)SqlConnectionSqlCommandSqlDataAdapter执行IDisposable,应予以处置(见此);2)没有必要执行cmd.ExecuteNonQuery(); .