Tyler Tyler - 2 months ago 8
C# Question

Search for value in radGridView using C# just finds values in first row of radGridView

I'm trying to search for a value in a

radGridView
in C#. I found many solutions about that but for some reason it just searches in the first row of my
GridView
. You can see my code here:

private void btnSearch_Click(object sender, EventArgs e)
{
if (txtSearch.Text == "")
{
MessageBox.Show("Please fill in the textbox!");
return;
}

else
{
gridViewContact.SelectionMode = GridViewSelectionMode.FullRowSelect;

foreach (GridViewRowInfo row in gridViewContact.Rows)
{
if (row.Cells[0].Value.ToString().Contains(txtSearch.Text) || row.Cells[1].Value.ToString().Contains(txtSearch.Text) || row.Cells[2].Value.ToString().Contains(txtSearch.Text))
{
row.IsSelected = true;
break;
}

else
{
MessageBox.Show("Nothing found!");
return;
}
}
}
}


But if I search for a value, it always shows me the message box "Nothing found...". Except when I search for a value which is in the first row. So it just finds the values in the first row and nowhere else.

Any suggestions?

PS: I'm using Telerik controls

EDIT: Here you can see the gridView:

enter image description here

Answer

I think your MessageBox is misplaced. Try this:

private void btnSearch_Click(object sender, EventArgs e)
{
    if (txtSearch.Text == "")
    {
        MessageBox.Show("Please fill in the textbox!");
        return;
    }

    else
    {
        gridViewContact.SelectionMode = GridViewSelectionMode.FullRowSelect;

        bool found = false;
        foreach (GridViewRowInfo row in gridViewContact.Rows)
        {
            if (row.Cells[0].Value.ToString().Contains(txtSearch.Text) || row.Cells[1].Value.ToString().Contains(txtSearch.Text) || row.Cells[2].Value.ToString().Contains(txtSearch.Text))
            {
                found = true;
                row.IsSelected = true;
                break;
            }
        }
        if (!found)
        {
            MessageBox.Show("Nothing found!");
        }
    }
}
Comments