Reputation: 105
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) { }
}
Upvotes: 6
Views: 12793
Reputation: 112362
This is because the second assignment replaces the first one
myDataTable.DefaultView.RowFilter = "firstFilter";
myDataTable.DefaultView.RowFilter = "secondFilter";
// Now RowFilter is "secondFilter"
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 + "%'";
It becomes clearer with String.Format
:
view.RowFilter = String.Format("Customer_Name LIKE '%{0}%' OR Reg_Number LIKE '%{0}%'",
escapedText);
or, since C# 7.0, with string interpolation:
view.RowFilter =
$"Customer_Name LIKE '%{escapedText}%' OR Reg_Number LIKE '%{escapedText}%'";
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';
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 + "%'";
}
Upvotes: 7
Reputation: 1437
I think you need OR operation instead of AND "Customer_Name like '%" + radTextBoxControl1.Text + "%' OR Reg_Number like '%" + radTextBoxControl1.Text + "%'";
Upvotes: 1
Reputation: 18443
This should work:
((DataTable)radGridView1.DataSource).DefaultView.RowFilter =
"Customer_Name like '%" + radTextBoxControl1.Text + "%' AND Reg_Number like '%" + radTextBoxControl1.Text + "%'";
Upvotes: 2