Home

C# Filter DataTable To New DataTable

Blog Date 6 December 2021

The Code

        DataTable dt = //get or create new table;

        string qwe = "Data1 LIKE '*";
        qwe += MySearch.Text;
        qwe += "*' OR Data2 LIKE '*";
        qwe += MySearch.Text;
        qwe += "*' OR Data3 LIKE '*";
        qwe += MySearch.Text;
        qwe += "*' OR Data4 LIKE '*";
        qwe += MySearch.Text;
        qwe += "*'";

        DataRow[] SelectedRows = dt.Select(qwe);

        DataTable FilteredTable = SelectedRows.CopyToDataTable();

        MyGrid.DataSource = FilteredTable;
        MyGrid.DataBind();

The Explanation

Datatables are handy. Ideally you SHOULD filter your datatable when you create it. Typically you'd filter by changing the SELECT statement in your SQL or however else your data is acquired or created. But life ain't perfect. Once you have that data you may wish to avoid another call to the SQL server or you may be filtering to simply clean up the display. Whatever your reasons are, they are...

So we have ourselved the datatable, dt. We create a search string, in this case "qwe". The syntax is roughly...

DataTable.RowName = 'what to look for'
DataTable.RowName LIKE '*what to look for*'
AND OR

The filtering is odd. When we apply the datatable.select method we get back DATAROWS!!! Not the original datatable OR a new datatable. We get back DATAROWS.

We can loop through these rows
    foreach(DataRow MyRow in SelectedRows)
    {
        MyTextBox.Text = MyRow["MyFieldName"];
        MyTextBox2.Text = MyRow["MyFieldName2"];
    }

Or if we are using a DataGrid, Repeater or whatnot we have to create a NEW datatable to bind the grid with, thus
    DataTable MyFilteredTable = MySelectedRows.CopyToDataTable();

And then bind as usual to the new table.


Need help? Contact ren@techsolus.co.uk

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog