行过滤器中的多个参数 [英] Multiple parameter in Row Filter
问题描述
我正在尝试将文本框作为 Rowfilter 放在 textchanged 事件下!
I am trying to put a textbox as an Rowfilter under a textchanged event !
下面的代码用于 GRID 以获取在文本框中输入的相应 Reg_Number
或 Customer_Name
!
The code below is used to GRID to get the appropriate Reg_Number
or Customer_Name
which is entered in the text box!
令人惊讶的事实是,这段代码直接采用了第二个参数
wat's the surprising fact is, this code directly takes the 2nd Argument
(即)((DataTable)radGridView1.DataSource).DefaultView.RowFilter = "Reg_Number like '%" + radTextBoxControl1.Text + "%'";
尝试切换线路,但无论我做什么,它都会忽略第一个并使用第二个
tried to switch the lines, but no matter what i did, it ignores the 1st one and takes the 2nd
我尝试将 AND 放在一行中,但不起作用,请帮帮我!
i tried to put AND to get both in a single line, bt din't work, plz hel me frnzz!
private void radTextBoxControl1_TextChanged(object sender, EventArgs e)
{
try
{
((DataTable)radGridView1.DataSource).DefaultView.RowFilter =
"Customer_Name like '%" + radTextBoxControl1.Text + "%'";
((DataTable)radGridView1.DataSource).DefaultView.RowFilter =
"Reg_Number like '%" + radTextBoxControl1.Text + "%'";
}
catch (Exception) { }
}
推荐答案
这是因为第二个作业取代了第一个作业
This is because the second assignment replaces the first one
myDataTable.DefaultView.RowFilter = "firstFilter";
myDataTable.DefaultView.RowFilter = "secondFilter";
// Now RowFilter is "secondFilter"
您必须将 2 个过滤器与逻辑 OR 组合在一起才能获得满足两个条件的结果:
You must combine the 2 filters with a logical OR to get results fulfilling both conditions:
myDataTable.DefaultView.RowFilter = "firstFilter OR secondFilter";
<小时>
var view = ((DataTable)radGridView1.DataSource).DefaultView;
string escapedText = radTextBoxControl1.Text.Replace("'", "''");
view.RowFilter = "Customer_Name LIKE '%" + escapedText + "%' OR " +
"Reg_Number LIKE '%" + escapedText + "%'";
使用 String.Format
会更清晰:
view.RowFilter = String.Format("Customer_Name LIKE '%{0}%' OR Reg_Number LIKE '%{0}%'",
escapedText);
或者,从 C# 7.0 开始,使用字符串插值:
or, since C# 7.0, with string interpolation:
view.RowFilter =
$"Customer_Name LIKE '%{escapedText}%' OR Reg_Number LIKE '%{escapedText}%'";
另外,请确保用两个单引号替换单引号.这使 SQL 字符串能够包含引号并防止 SQL 注入:
Also, make sure to replace single quotes by two single quotes. This enables the SQL string to contain quotes and prevents SQL-injections:
SELECT * FROM myTable WHERE Name = 'Andy''s Pub';
<小时>
您必须将这两个条件与 OR
结合而不是 AND
的原因是,用户将输入 either 客户名称 或一个注册号(我们只有一个文本框).
The reason you must combine both conditions with OR
, and not AND
is, that the user will enter either a customer name or a registration number (we have only one textbox).
或者,您可以检查条目的格式是否与注册号类似,并应用适当的过滤器.在伪代码中:
Alternatively, you could check, whether the entry is formatted like a registration number or not and apply the appropriate filter. In pseudo code:
if (radTextBoxControl1.Text is formatted as reg_nr) {
view.RowFilter = "Reg_Number LIKE '%" + escapedText + "%'";
} else {
view.RowFilter = "Customer_Name LIKE '%" + escapedText + "%'";
}
这篇关于行过滤器中的多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!