How to make a simple search / filter for dataGridView?

Yes, I have a Windows Form project created in Visual Studio C #. This is a telephone diary that I made from scratch. It works fine, but I just want to add another function to the user.

The user enters contacts, wants to add his data to the datagridview. And they can add them, they can edit them as needed while the program is running, they can add (import) more people from the excel file, and then export it to a new excel file. Thus, nothing is saved in the program, everything that they want to do should happen during the execution of the program and, if necessary, be exported to a new excel file.

So everything works fine, but I want the user to view the current data file (dataGridView1) in the program (in the application), and I cannot figure out how to do this.

I have it where the user can sort the columns in ascending / descending order (this is a built-in function of the data grid), but I would like to have a specific text search. I don’t want to do MySqlConnection and all this, I just want to, say, go to the search button and program it (by click) only on the search, where searchTextBox is equal to the value in any cell of my dataGridView1 and display only those results.

I don’t know why it is so hard to find, is it possible? I would have thought it would be easy, but I could not find out how to do it. Below is a picture of my application. Also, if you have any ideas on how to make this better for the user, it would be nice. (

Address Book / Phone Diary

+4
source share
1 answer

Just try look

    private void searchbutton_Click(object sender, EventArgs e)
    {
    string searchValue = searchtextBox.Text;
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        bool valueResult = false;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < row.Cells.Count; i++)
            {
                if (row.Cells[i].Value != null && row.Cells[i].Value.ToString().Equals(searchValue))
                {
                    int rowIndex = row.Index;
                    dataGridView1.Rows[rowIndex].Selected = true;
                    valueResult = true;
                    break;
                }
            }

        }
        if (!valueResult)
        {
            MessageBox.Show("Unable to find " + searchtextBox.Text, "Not Found");
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}
+4
source

Source: https://habr.com/ru/post/1612168/


All Articles