Vb.net dataTable / DataGridView search / sort

So, I have a dataGridView and a text field in the form. I want to be able to search through a dataGridView and sort it compared to a string in a text field. for example: I type "acv" in a text box, and all lines containing "acv" are sorted at the top. I do this with a bunch of gymnastics using datatable.select and some cleaning and stuffing, but it is ugly and slow. What would be the best practice / correct / normal way to do this?

+3
source share
2 answers

Use a filtered DataView, and then set the DataGridView BindingSource to a Filtered DataView. If the user clears the filter condition, simply set the BindingSource back to the original default view. I recommend that you keep the view before sorting so that you can easily return to the original dataview. I use it now for quick sorting and it works great. Replace the 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 the DataView at the beginning, then retrieve the DataView (i.e. DataSource) and modify. I'm not sure if you use 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()
+3
source

. , jQuery, . :

$(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');
})
}
0

Source: https://habr.com/ru/post/1723165/


All Articles