D B
D B

Reputation: 306

DataGridView multiple column search

I have currently got a single search working for 1 column. I am wanting to add multiple columns to the search. So i can search Student_FName, Student_SName and Student_Email

Below is the code i have currently got working. Do i need to add an OR statement in it? or is there another way of including multiple row filters

private void SearchTxt_TextChanged(object sender, EventArgs e)
        {
            try 
                { 

                    var bindData = (BindingSource)studentGridView.DataSource;
                    var dataTable = (DataTable)bindData.DataSource;
                    dataTable.DefaultView.RowFilter = string.Format("Student_Username LIKE '%{0}%'", SearchTxt.Text );
                    studentGridView.Refresh();

                }
            catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }

Upvotes: 1

Views: 9483

Answers (3)

Awais
Awais

Reputation: 21

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dgv1.DataSource;
        bs.Filter = "[ColumnName1] like '%" + textBox1.Text + "%' " +
            "OR [ColumnName2] like '%" + textBox1.Text + "%'" +
            "OR [ColumnName3] like '%" + textBox1.Text + "%'" +
            "OR [ColumnName4] like '%" + textBox1.Text + "%'";
        dgv1.DataSource = bs; 
    }

Upvotes: 2

ehh
ehh

Reputation: 3480

Use Select from Datatable

    private void SearchTxt_TextChanged(object sender, EventArgs e)
    {
        try 
            { 

                var bindData = (BindingSource)studentGridView.DataSource;
                var dataTable = (DataTable)bindData.DataSource;
                var rows = dataTable.Select (string.Format("Student_Username LIKE '%{0}%' AND [Some other filter]", SearchTxt.Text ));

                studentGridView.DataSource = rows.CopyToDataTable()
                studentGridView.Refresh();

            }
        catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
    }

Upvotes: 4

D B
D B

Reputation: 306

 private void SearchTxt_TextChanged(object sender, EventArgs e)
        {
            try 
                { 

                    var bindData = (BindingSource)studentGridView.DataSource;
                    var dataTable = (DataTable)bindData.DataSource;
                    dataTable.DefaultView.RowFilter = string.Format("Student_Username LIKE '%{0}%' OR Student_FName LIKE '%{0}%'", SearchTxt.Text );
                    studentGridView.Refresh();

                }
            catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }

Upvotes: 0

Related Questions