Home > Back-end >  How to bring rows with search results on top in the datagridview
How to bring rows with search results on top in the datagridview

Time:12-22

Am trying to search for values through the datagridview using a column, i have columns appliance type and appliances name , multiple appliances can have the same appliance, users will use the appliance type column to search

What i want is that when a user search for appliance type all the rows with the searched appliance type should come on top like some kind of sorting

Below is what i have tried but it only brings one row
Thanks in advance

private DataGridViewCell gettext(string searchtext,DataGridView dataGridView,int index)
        {
            dtgridappliance.MultiSelect = true;
            dtgridappliance.SelectionMode=DataGridViewSelectionMode.FullRowSelect;
            DataGridViewCell met = null;
            foreach(DataGridViewRow row in dataGridView.Rows)
            {
                for (int i = 0; i < row.Cells.Count; i  )
                {

                    if (row.Cells[index].Value != null && row.Cells[index].Value.ToString().ToLower().Contains(searchtext.ToLower()))
                    {
                        met = row.Cells[index];
                        dtgridappliance.Rows[index].Selected = true;
                        this.dtgridappliance.Sort(dtgridappliance.Columns[0],ListSortDirection.Ascending);
                        dtgridappliance.FirstDisplayedScrollingRowIndex = dtgridappliance.SelectedRows[i].Index;
                        break;
                    } 
                }
            }
            return met;
        }


CodePudding user response:

Your question is How to bring rows with search results on top in the datagridview and your current approach is attempting to use datagridview with sort


The sort requires a way to compare a given Appliance to the type selected in the combo box:

private int compareToSelectedType(Appliance appliance)
{
    return appliance.ApplianceType.Equals(comboBoxSearch.SelectedItem) ?
        0 : 1; // Ones that match will sort before ones that don''t.
}

Now, when the combo box changes, you can remove all the DataGridView items and put them back in a different order.

private void onSearchByApplianceType(object? sender, EventArgs e)
{
    // Use System.Linq to sort a new temporary list.
    var tmp = new List<Appliance>(
        Appliances
        .OrderBy(_=>compareToSelectedType(_))
        .ThenBy(_=>_.Name));

    // Remove all items from the DataGridView
    Appliances.Clear();

    // Put them back in with the new order.
    foreach (var appliance in tmp)
    {
        Appliances.Add(appliance);
    }
}

This is "just one way" to do it, but I tested it and it works. Hope this helps get you closer to your intended outcome.

  • Related