Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Multi Column Value Search in DataGridView

4.46/5 (9 votes)
23 May 2011CPOL 63.4K   2.8K  
This post helps to search multiple cell values of the provided columns in a datagridview

Introduction

This post will help you to search multiple cell values of the provided columns in a datagridview.

MultiColumnValueSearch/image.png

The Add/Delete button adds/deletes rows in the top datagridview, were the user can enter the search criteria.

The bottom datagridview is the grid in which we perform search.

The first column of the top datagridview lists all the column names of the bottom datagridview. The user has to enter the search value in the second column.

This property gets the search criteria from the top datagridview:

C#
/// <summary>
/// Returns Dictionary(columnName, searchValue)
/// </summary>
private Dictionary<string, string> SearchList
{
    get
    {
        Dictionary<string, string> searchList = new Dictionary<string, string>();
        foreach (DataGridViewRow dgvRow in dataGridViewSearch.Rows)
        {
            string colName = Convert.ToString(dgvRow.Cells["ColumnName"].Value);
            //ignore rows which have no "ColumnName" assigned
            if (colName != string.Empty)
            {
                string val = Convert.ToString(dgvRow.Cells["Value"].Value);
                searchList.Add(colName, val);
            }
        }
        return searchList;
    }
}

This routine performs the search operation and returns the matched datagridviewrows as list:

C#
/// <summary>
/// Perform Search in the provided datagridview
/// with the Dictionary(columnName, searchValue)
/// </summary>
/// <param name="dgView"></param>
/// <param name="searchList"></param>
/// <returns>List of rows which satisfy the search criteria</returns>
private List<DataGridViewRow> PerformSearch
(DataGridView dgView, Dictionary<string, string> searchList)
{
    bool rowFound = false;
    List<DataGridViewRow> dgvSearchResult = new List<DataGridViewRow>();
    foreach (DataGridViewRow dgvRow in dgView.Rows)
    {
        foreach (string colName in searchList.Keys)
        {
            string val1 = Convert.ToString(dgvRow.Cells[colName].Value);
            string val2 = Convert.ToString(searchList[colName]);
                     
            //Ignore case and compare values
            if (string.Compare(val1, val2, true) == 0)
                rowFound = true;
            else
            {
                //Stop searching other cell values, if in the wrong row
                rowFound = false;
                break;
            }
        }
        if (rowFound)
            dgvSearchResult.Add( dgvRow);
    }
    return dgvSearchResult; 
}

Search Button Click event is defined below:

C#
private void btnSearch_Click(object sender, EventArgs e)
{
    lblInfo.Text = string.Empty;

    //Check if the search column Name repeats
    List<string> colNameList = new List<string>();
    foreach (DataGridViewRow dgvRow in dataGridViewSearch.Rows)
        if (!colNameList.Contains(Convert.ToString(dgvRow.Cells["ColumnName"].Value)))
            colNameList.Add(Convert.ToString(dgvRow.Cells["ColumnName"].Value));
        else
        {
            MessageBox.Show("Invalid Search criteria", "Search", 
            MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        //Perform search and get the result rows
        List<DataGridViewRow> resultRows = PerformSearch(dataGridView1, SearchList);
 
        //Deselect all Cells in the gridview
        if (this.dataGridView1.SelectedCells.Count > 0)
            foreach (DataGridViewCell dgvCell in this.dataGridView1.SelectedCells)
            dgvCell.Selected = false;

        if (resultRows.Count > 0)
        {
            //Select the rows which satisfy the search criteria
            foreach (DataGridViewRow dgvRow in resultRows)
                dataGridView1.Rows[dgvRow.Index].Selected = true;
        }

    lblInfo.Text = resultRows.Count.ToString() + " Match(s) Found";
}

The attached source code is in VS 2010.

Thanks,
Balu

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)