简体   繁体   中英

C# Datagridview filter using textbox and button

I want to filter my datagridview using click event, I'm using the following code:

BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView3.DataSource;
        bs.Filter = dataGridView3.Columns[0].HeaderText.ToString() + " LIKE '%" + textBox1.Text + "%'";
        dataGridView3.DataSource = bs;

This works for my other datagridviews, but it shows an error for this datagridview3 : Cannot perform 'Like' operation on System.Int32 and System.String .

Here is the datagridview3 in a screenshot to show which data it is holding:

I guess you have to convert the value you get from textBox1.Text to a number. the data in the first column is numeric, and this comparing text ( string ) vs a numeric value isn't supported.

Here are some ways of converting to an integer value:

int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);

Once you have succesfully converted, you can adapt your code and try to see if it works that way:

BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView3.DataSource;
        bs.Filter = dataGridView3.Columns[0].HeaderText.ToString() + " LIKE '%" + Convert.ToInt32(textBox1.Text) + "%'";
        dataGridView3.DataSource = bs;

NOTE : Make sure to check whether the use has entered a valid number before hitting the search button ofcourse. Otherwise you'll still receive an error that the value couldn't be parsed/converted to a number.

Hope all of this helps you a bit more.

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