Search code examples
c#datagridviewtextbox

How to filter datagridview with textbox and button click in C#?


I would like to filter my dataGridView (birthDay colum by month) for button click with a textbox.

If I type number 5 for the textbox, then I would display the rows which are containing number 5 as from month row.

var dataTable = (DataTable)DataGridView2.DataSource;
var dataView = dataTable.DefaultView;
dataView.RowFilter = string.Format("Month", birthdayMonth.Text);
DataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;   
DataGridView2.Rows[0].Selected = true;

Solution

  • Filtering DataGridView by a using textbox & two DataGridView without database

    1. Make sure to add 2 DataGridViews
    2. implement a .csv reader
    3. Put a TextBox
    4. Name them properly (textbox, 2 dgv)

    In the first DataGridview create a Selection Changed event for the first DataGridView.

    I used this method:

    if (this.dgv2.DataSource != null)

    • this.dgv2.DataSource = null;

    else

    • this.dgv2.Rows.Clear();

    for (int i = 0; i < dgv1.SelectedRows.Count; i++)

    • int index = dgv2.Rows.Add();

    Then you can inser the wanted rows like:

    • dgv2.Rows[index].Cells["to"].Value = dgv1.SelectedRows[i].Cells["from"].Value.ToString();

    After creating the Selection Changed event for the first DataGridView we have create a text based search, it can be with foreach loop.

    Example: foreach (DataGridViewRow row in dgv.Rows)

    Then if and else methods

    Like:

    if ((string)row.Cells["from"].Value == textbox.Text)

    Making statements:

    • row.Selected = false;

    • row.Visible = true;

    else

    • row.Selected = false;

    • row.Visible = false;

    Enjoy! :)