(C#) search number in dataGridView1 ?

LeaV 81 Reputation points
2023-01-31T21:55:13.58+00:00

Hello everyone!

Im trying to search a number in a dataGridView1. When I try to Search for texts, it work perfect. But, when I try to search for numbers, it's not working. In my column I have numbers like: 1, 2, 12, 22, 33... So, When i type: 2 in the textBox1, for the result in dataGridView1 I get rows with numbers 2, 12 , 22. I'd like to see for the result in dataGridView1 only rows with numbers 2.

Please for your help. Thanks in advance.

My code:


private void Button1_Click(object sender, EventArgs e)
        {
            string searchValue = textBox1.Text;
            string colName = dataGridView1.Columns[1].Name;//Column Number of Search
            ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName + " like '%{0}%'", searchValue.Trim().Replace("'", "''"));
        }
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,836 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2023-02-01T02:24:34.09+00:00

    @LeaV, Welcome to Microsoft Q&A, based on my test, I reproduced your problem. If we used the number as the column name, we need to add [] for that column in the RowFilter string.

    Here is a code example you could refer to.

      private void button1_Click(object sender, EventArgs e)
            {
                string text = textBox1.Text;
                string colName = dataGridView1.Columns[1].Name;//Column Number of Search
                ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName + " = '{0}'", text.Trim().Replace("'", "''"));
            }
    
    

    Tested Result:

    User's image


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful