[c#] Search for value in DataGridView in a column

I want the user to be able to search for a number in a column in the DataGridView (dgv). The dgv can hold many records. Each record has a Project Number. So I want the user to be able to search for a project number in column Project Number. The columns I have are: ProjectID(not visible); Image(no headertext); Project Number; Project Name; Company; Contact.

Here is my code:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;
    int rowIndex = -1;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[row.Index].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dgvProjects.Rows[row.Index].Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Problem #1: What it does so far: The user types the project number in TextBox1. When he/she clicks the button, the code searches for this string in the rows, and when found the project number, that row gets selected. It works fine, but only once. When I want to search for an other project number, nothing happens.

Problem #2: I think this can be done in a better way, by searching the values for column Project Name only. But how should I do this properly?

The code I used to search comes from this answer

This question is related to c# winforms datagridview datagridviewcolumn

The answer is


Why don't you build a DataTable first then assign it to the DataGridView as DataSource:

DataTable table4DataSource=new DataTable();

table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");

...

(add your rows, manually, in a circle or via a DataReader from a database table) (assign the datasource)

dtGrdViewGrid.DataSource = table4DataSource;

and then use:

(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();

You can even put this piece of code within your textbox_textchange event and your filtered values will be showing as you write.


It's better also to separate your logic in another method, or maybe in another class.

This method will help you retreive the DataGridViewCell object in which the text was found.

    /// <summary>
    /// Check if a given text exists in the given DataGridView at a given column index
    /// </summary>
    /// <param name="searchText"></param>
    /// <param name="dataGridView"></param>
    /// <param name="columnIndex"></param>
    /// <returns>The cell in which the searchText was found</returns>
    private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
    {
        DataGridViewCell cellWhereTextIsMet = null;

        // For every row in the grid (obviously)
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            // I did not test this case, but cell.Value is an object, and objects can be null
            // So check if the cell is null before using .ToString()
            if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
            {
                // the searchText is equals to the text in this cell.
                cellWhereTextIsMet = row.Cells[columnIndex];
                break;
            }
        }

        return cellWhereTextIsMet;
    }

    private void button_click(object sender, EventArgs e)
    {
        DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
        if (cell != null)
        {
            // Value exists in the grid
            // you can do extra stuff on the cell
            cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
        }
        else
        {
            // Value does not exist in the grid
        }
    }

//     This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
    string searchValue=textBoxSearch.Text;
    int rowIndex = 1;  //this one is depending on the position of cell or column
    //string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        bool valueResulet = true;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dataGridView1.Rows[rowIndex].Selected = true;
                rowIndex++;
                valueResulet = false;
            }
        }
        if (valueResulet != false)
        {
            MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;

How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?

I use this code to get the data out:

con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();

DataTable dt = new DataTable();

adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
adapt.Fill(dt);        
dataGridView1.DataSource = dt;
con.Close();

Filter the data directly from DataTable or Dataset:

"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
   this.dataGridView1.DataSource = "MyTable".DefaultView;

Use this code on event KeyUp of Textbox, replace "MyTable" for you table name or dataset, replace for the field where you want make the search.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results

Examples related to datagridviewcolumn

Search for value in DataGridView in a column Get a DataTable Columns DataType How to hide column of DataGridView when using custom DataSource? How can I right-align text in a DataGridView column?