简体   繁体   中英

C# Filtering number on datagridview

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM