Reputation: 97
I have a one textbox
, one combobox
and one datagridview
and datagridview have some data on it.Combobox carry information about datagridview coloumn name.When I write text on textbox datagridview will be filtered according to column name which is in combobox.The code is given is not working when I try to write number on textbox It gave me error something like
'Cannot perform 'Like' operation on System.Double and System.String.'.
What I must do here for work.
string rowFilter = string.Format("[{0}] like '%{1}%'", combobox.Text, textBox1.Text);
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = rowFilter;
Upvotes: 1
Views: 1487
Reputation: 53958
This is reasonable. You cannot apply the LIKE SQL operator to numbers.
You could fix this like below:
double number;
string rowFilter = double.TryParse(textBox1.Text, out number) ?
string.Format("[{0}]='{1}'", combobox.Text, textBox1.Text) :
string.Format("[{0}] like '%{1}%'", combobox.Text, textBox1.Text);
The method TryParse
of double is used when we want from parsing a string to create a double. If this is possible, the string is the string representation of a double, then the method performs the conversion and returns true
. The converted number is stored in out variable. While when the conversion fails, it returns false
. Given that and using the ternary operator, ?
, we can create the correct filter in all cases.
Upvotes: 1