行过滤器中的多个参数

时间:2013-03-03 13:53:07

标签: c# winforms

我正在尝试将文本框作为Rowfilter置于textchanged事件下!

以下代码用于GRID以获取在文本框中输入的相应Reg_Number Customer_Name

wat的令人惊讶的事实是,此代码直接采用第二个参数

(即)
((DataTable)radGridView1.DataSource).DefaultView.RowFilter = "Reg_Number like '%" + radTextBoxControl1.Text + "%'";

尝试切换线条,但无论我做了什么,它都会忽略第一个并取得第二个

我试图把AND放在一条线上,但是不行,请告诉我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) { }
}

3 个答案:

答案 0 :(得分:6)

这是因为第二个作业取代了第一个作业

myDataTable.DefaultView.RowFilter = "firstFilter";
myDataTable.DefaultView.RowFilter = "secondFilter";
// Now RowFilter is "secondFilter"

您必须将2个过滤器与逻辑OR组合以获得满足以下两个条件的结果:

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以来,使用字符串插值:

view.RowFilter =
    $"Customer_Name LIKE '%{escapedText}%' OR Reg_Number LIKE '%{escapedText}%'";

另外,请确保用两个单引号替换单引号。这使SQL字符串能够包含引号并防止SQL注入:

SELECT * FROM myTable WHERE Name = 'Andy''s Pub';

您必须将这两个条件与OR合并而不是AND的原因是,用户将输入 客户名称注册号码(我们只有一个文本框)。

或者,您可以检查条目是否格式化为注册号,并应用适当的过滤器。在伪代码中:

if (radTextBoxControl1.Text is formatted as reg_nr) {
    view.RowFilter = "Reg_Number LIKE '%" + escapedText + "%'";
} else {
    view.RowFilter = "Customer_Name LIKE '%" + escapedText + "%'";
}

答案 1 :(得分:2)

这应该有效:

((DataTable)radGridView1.DataSource).DefaultView.RowFilter =
    "Customer_Name like '%" + radTextBoxControl1.Text + "%' AND Reg_Number like '%" + radTextBoxControl1.Text + "%'";

答案 2 :(得分:1)

我认为你需要OR操作而不是AND "Customer_Name like '%" + radTextBoxControl1.Text + "%' OR Reg_Number like '%" + radTextBoxControl1.Text + "%'";