Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridview search: show only searchresult and hide other rows?

What should I add to my code to only show the results of my search?

Right now when I search the searchresult becomes selected (highlighted) and the others remain the same.

Been trying to hide the other rows but without any success (and only show the searchresult, alone). Any suggestions? Im using a datagridview.

My code:

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

    for (int i = 0; i < dgTest.Rows.Count; i++)
    {
        if (dgTest.Rows[i].Cells[0].Value.ToString() == search)
        {
            dgTest.Rows[i].Selected = true;
            break;
        }
        else
        {
            dgTest.Rows[i].Selected = false;
        }
    }
}
like image 401
user1773766 Avatar asked Oct 25 '12 10:10

user1773766


2 Answers

If your DataGridView is not bound to a data source, then setting the row's Visible property to false will hide it:

for (int i = 0; i < dgTest.Rows.Count; i++)
    {
        var row = dgTest.Rows[i];

        if (row.Cells[0].Value.ToString() == search)
        {
            row.Selected = true;
            row.Visible = true;
        }
        else
        {
            row.Selected = false;
            row.Visible = false;
        }
    }

(I removed the 'break' command, as even after you have found the matching row, you would want to continue and hide the other rows.)

If you're using DataBinding, though, it's not so easy, as shown in this page.

like image 54
stuartd Avatar answered Nov 08 '22 05:11

stuartd


you can try this:

for (int i = 0; i < dgTest.Rows.Count; i++)
{
    if (dgTest.Rows[i].Cells[0].Value.ToString() == "search")
    {
        dgTest.Rows[i].Selected = true;
        dgTest.Rows[i].Visible = true;
    }
    else
    {
        dgTest.Rows[i].Visible = false;
        dgTest.Rows[i].Selected = false;
    }
}
like image 42
Rohit Vyas Avatar answered Nov 08 '22 05:11

Rohit Vyas