C# WPF-按名称和文本框筛选Datagrid
我用这段代码用一个文本框过滤我的dataGrid,它可以按Id过滤,但是如果我把它改成按名称过滤(我只是把查询中的“Id”改成“Name”),它就不起作用了,类似于输入文本的“Column Name”“无效。当查询设置为Id并输入字母时,同样的错误也会发生,显然它只适用于数字 代码如下:C# WPF-按名称和文本框筛选Datagrid,c#,wpf,filter,datagrid,C#,Wpf,Filter,Datagrid,我用这段代码用一个文本框过滤我的dataGrid,它可以按Id过滤,但是如果我把它改成按名称过滤(我只是把查询中的“Id”改成“Name”),它就不起作用了,类似于输入文本的“Column Name”“无效。当查询设置为Id并输入字母时,同样的错误也会发生,显然它只适用于数字 代码如下: private void textBox_TextChanged(object sender, TextChangedEventArgs e) { try {
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进行过滤是一种完美的想法,但它对用户不是很友好。谢谢您需要用
包装您的过滤器。
所以这句话:
query += " where Nome =" + textBox.Text;
变成
query += " where Nome ='" + textBox.Text + "'";
注意这是一个快速解决方案,你需要考虑@丹尼斯回答< /p> < p>不要使用字符串连接来生成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)
SqlConnection
,SqlCommand
,SqlDataAdapter
实现IDisposable
,并应予以处置(请参阅);2) 不需要执行cmd.ExecuteNonQuery()代码>可能是打字错误:query+=“where Nome=“+textBox.Text代码>Nome还是Name?Nome是葡萄牙语的名字,所以我只是翻译了一下,让你们更好地理解它,但是“Nome”是正确的^^您有哪种异常
异常?System.Data.SqlClient.SqlException类型的未处理异常发生在System.Data.dll中其他信息:列名称“您在文本框中输入的字母”无效。这非常有效@ZwoRmi,非常感谢=我明白您的意思,我只是不明白如何在文本中使用这个,因为我是新来的。