views:

1633

answers:

2

So I have a dataGridView and a textbox on a form. I want to be able to search through the dataGridView and sort it compared to the string in the text box. ex: I type "acv" in the text box and all strings containing "acv" are sorted to the top. I'm accomplishing this with a bunch of gymnastics involving datatable.select and some clearing and filling but it's ugly and slow. What would be the best practice/proper/normal way to do this?

A: 

Take a look at this tutorial. I used the same idea of it's table filtering using jQuery and it worked out pretty well for me. Here's what I used:

$(document).ready(function() 
{    
$('#filter').keyup(function(event) 
{
    //if esc is pressed or nothing is entered        
    if (event.keyCode == 27 || $(this).val() == '') 
    {
        //if esc is pressed we want to clear the value of search box
        $(this).val('');

        //we want each row to be visible because if nothing
        //is entered then all rows are matched.
        $('tbody tr').removeClass('visible').show().addClass('visible');
    }
    else 
    {
        // drill down and find the ONE table out of many.
        var theTable = $('div.rgDataDiv').find('table.rgMasterTable').find('tbody tr');

        //if there is text, lets filter
        filter(theTable, $(this).val());
    }
});    
});


//filter results based on query
function filter(selector, query) 
{
query =    $.trim(query); //trim white space
query = query.replace(/ /gi, '|'); //add OR for regex

$(selector).each(function() 
{
    ($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
})
}
Chris
+1  A: 

Use a filtered DataView and then set your DataGridView's BindingSource to the Filtered DataView. If the user clears the filter condition, then just set the BindingSource back to your original default view. I recommend you store the view before sorting so you can go back to the original dataview easily. I use this now for sorting fast and it works great. Replace column names with yours. You should be able to modify the dataview from the original DataGridView and apply the filter without re-binding. Just bind your DataGridView to a DataView at the beginning, then retrieve the DataView (i.e. DataSource) and modify. I'm not sure if you are using a BindingNavigator or not. Good luck.

Dim myDataTable As DataTable = myDataSet.Tables(0)
Dim myDataView As New DataView(myDataTable)

myDataView.RowFilter = "CompanyName LIKE '%" & ddlAlpha.SelectedItem.Text & "%'"
myDataView.Sort = "ContactName"
dataGridView1.DataSource = myDataView
dataGridView1.DataBind()
0A0D