简体   繁体   中英

C# - Searching across more than one column

Two questions:

  1. How would you merge the two bits of code? Seems a bit redundant to have them as two large chunks!

  2. How would you go about searching by more than one column (and return a result if it is found in any of the following columns: name, gender, age )?

     private void button1_Click(object sender, EventArgs e) { BindingSource bs = new BindingSource(); bs.DataSource = dataGridView1.DataSource; bs.Filter = "id like '%" + textBox1.Text + "%'"; dataGridView1.DataSource = bs; } private void textBox1_TextChanged(object sender, EventArgs e) { BindingSource bs = new BindingSource(); bs.DataSource = dataGridView1.DataSource; bs.Filter = "id like '%" + textBox1.Text + "%'"; dataGridView1.DataSource = bs; } 

Answer to your 1st Question :

Create a function to have your searching statements and call it whenever you required.as below:

        private void button1_Click(object sender, EventArgs e)
        {
           SearchData();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
             SearchData();
        }
        private void SearchData()
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = dataGridView1.DataSource;
            bs.Filter = "id like '%" + textBox1.Text + "%'";
            dataGridView1.DataSource = bs;
         }

Answer to your 2nd Question :

you can write Filter as below:

bs.Filter = "id like '%" + textBox1.Text + "%' and name like '%" + textBox2.Text + "%'";

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