Search for value in DataGridView in a column
Asked Answered
M

10

8

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

Mosley answered 1/11, 2012 at 9:9 Comment(0)
S
24

Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:

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

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[2].Value.ToString().Equals(searchValue))
            {
                row.Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}
Smash answered 1/11, 2012 at 9:19 Comment(2)
Thanks, I already thought of something like this, but back then I used the wrong value... This solved both problemsMosley
Is dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect; necessary? It is not enough to use the foreach loop?Penult
P
6

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.

Persecution answered 30/6, 2014 at 22:13 Comment(0)
S
2

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
        }
    }
Shannan answered 15/2, 2017 at 16:39 Comment(0)
M
1
//     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);
    }
}
Migdaliamigeon answered 8/1, 2014 at 10:11 Comment(0)
I
1

I'm can solve it simply:

    public static int SearchDGV(DataGridView dgv, string SearchValue, string ColName)
    {
        foreach (DataGridViewRow Row in dgv.Rows)
        {
            if (Row.Cells[ColName].Value.ToString().Equals(SearchValue))
                return Row.Index;
        }
        return -1;
    }
Interactive answered 19/9, 2022 at 15:34 Comment(0)
A
0

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.

Anthroposophy answered 7/8, 2014 at 18:3 Comment(0)
G
0

"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();
Gyromagnetic answered 12/4, 2016 at 15:16 Comment(1)
Though you do not yet have the reputation to comment, this is not an answer to the questionGarrot
B
0
 private void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            string searchValue = txtSearch.Text;
            string colName = dataGridView1.Columns[1].Name;//Column Number of Search
            ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName+" like '%{0}%'", searchValue.Trim().Replace("'", "''"));
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
      
    }

    private void txtSearch_TextChanged(object sender, EventArgs e)
    {
        btnSearch_Click(null,null);
    }
Barvick answered 5/1, 2022 at 22:53 Comment(0)
S
0
private void txtSearch_TextChanged(object sender, EventArgs e)
{
     string searchValue = txtSearch.Text;
     for (var i = 0; i <= dgvList.RowCount; i++)
     {
          for (var j = 0; j <= dgvList.ColumnCount; j++)
          {
               if ((dgvList.Item(j, i).FormattedValue.ToString.ToLower).ToString.Contains(searchValue.ToString.ToLower))
               {
                    Console.Writeline("found");
                    dgvList.Item(j, i).Selected = true;
                    return;
               }
          }
     }
     
}

This method will search all rows and cells in the DataGridView, If result is true then select the row.

Slater answered 27/4, 2022 at 17:21 Comment(0)
C
0
  private void textBox3_TextChanged(object sender, EventArgs e)
        {
            DataView dv = ds.Tables["todo"].DefaultView;
            dv.RowFilter = "topic LIKE '" + textBox3.Text + "%'";
            dataGridView1.DataSource = dv;
        }
Closed answered 9/1, 2023 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.