6

I am trying to put a textbox as an Rowfilter under a textchanged event !

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

(i.e)
((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

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) { }
}
4

3 回答 3

7

这是因为第二个赋值替换了第一个

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';

您必须将这两个条件与 结合起来的原因ORAND,用户将输入客户名称或注册号我们只有一个文本框)。

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

if (radTextBoxControl1.Text is formatted as reg_nr) {
    view.RowFilter = "Reg_Number LIKE '%" + escapedText + "%'";
} else {
    view.RowFilter = "Customer_Name LIKE '%" + escapedText + "%'";
}
于 2013-03-03T13:58:51.667 回答
2

这应该有效:

((DataTable)radGridView1.DataSource).DefaultView.RowFilter =
    "Customer_Name like '%" + radTextBoxControl1.Text + "%' AND Reg_Number like '%" + radTextBoxControl1.Text + "%'";
于 2013-03-03T13:56:16.343 回答
1

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

于 2013-03-03T14:01:09.520 回答