Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a simple dataGridView search / filter?

Yeah, I have an event-driven Windows Form project made in Visual Studio C#. It's a telephone diary that I made from scratch. It is actually working fine but I just want to add another feature for the user.

The user enters the contacts, wants to add to the datagridview with their details. And they can add them, can edit them as needed while the program is running, can add (import) more people from an excel file, and then can export it to a new excel file. So nothing is saved to the program, everything they want to do has to happen during runtime of the program and be exported to new excel file as needed.

So everything works fine but I want to let the user search the current datagrid (dataGridView1) in the program (in-app) and I can't figure out how.

I have it where the user can sort the columns ascending / descending (that is a built in feature of the data grid), but I would like to have the specific text search. I don't want to make a MySqlConnection and all of that, I just want to be able to, say, go into the search button and program it (on click) to only search where searchTextBox is equal to a value in any cell of my dataGridView1, and display only those results.

Not sure why it's so difficult to find, is it possible? I would think it would be simple, but I haven't been able to find out how to do it. Below is a picture of my application as of now. Also if you happen to have any ideas as to how to make it better for the user that would be nice. (:

Address book / telephone diary

like image 966
Chris Koro Avatar asked Oct 18 '15 23:10

Chris Koro


1 Answers

Just try this , Have a 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);
    }
}
like image 114
Anoop B.K Avatar answered Nov 15 '22 03:11

Anoop B.K