How to filter rows in DataSet using C#

No.of Views2604
Bookmarked0 times
Downloads 
Votes0
By  ninethsense   On  23 May 2010 05:05:32
Tag : CSharp , General
This article explains how to filter rows in a DataSet/DataTable. The example provided will help you get information faster.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

This article is a demonstration of filtering a DataSet/DataTable with the Select method. and  beginners and will help them in learning the language basics.

Image Loading

Overview

This is just a hobby program which I thought will be helpful for .NET beginners.

Using the code

The sample code contains only a WinForm which loads some rows with random data. I have added a ListBox with ready made filter expressions and there is a TextBox which will help you to enter user-defined filter expressions.

There is a DataTable I use in this application as a global - parent datatable. I apply filter expressions on this. This DataTable is a dynamically created one. The LoadData() method is used to fill random data into this DataTable.

 

DataTable dt = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
    dt.Columns.Add("A");
    dt.Columns.Add("B");
    LoadData();
}

The LoadDate() method is shown below. Notice the usage of Random(). The same method is associated with the 'Reset Data' button.

private void LoadData()
{
    dt.Rows.Clear();
    Random r = new Random();for (int i = 0; i < 10; i++)
    {
        DataRow dr = dt.NewRow();
        dr["A"] = r.Next(0, 1000);
        dr["B"] = r.Next(0, 1000);
        dt.Rows.Add(dr);
    }

    dataGridView1.DataSource = dt;
}

 Next is the most important method in this application. This is the method which gives 'life' to this application: the DoFilter() method. You can pass the filter expression as a string to this method and the effect can be seen on the DataGridView attached.

private void DoFilter(string filter)
{
    DataTable dt1 = dt.Clone();try{foreach (DataRow dr in dt.Select(filter))
    {
        dt1.ImportRow(dr);
    }
        dataGridView1.DataSource = dt1;
    }catch// Warning: Non-standard! - without proper catching of exception{
        MessageBox.Show("Error in filter expression");
    }
}

 If you give an invalid filter expression, the application will show an 'Error in filter expression' message. You may have noticed the dt.Select(filter) in the above code. As you know, this is the key of this article which does the filtering job. Since dt.Select() returns an array of DataRows, I used a temporary table with the same structure (dt.Clone()) to import the filtered results and bind it to DataGridView.

Generic method

Here is a generic method overview for your projects. Please do not use this as it is since I wrote this function/method as a part of writing this article and it is not properly tested.

private DataTable DoDataTableFilter(DataTable dt, string filter)
{
    DataTable dt1 = dt.Clone();foreach (DataRow dr in dt.Select(filter))
    {
        dt1.ImportRow(dr);
    }return dt1;
}

 Conclusion

Note that since this is a very simple and quickly-made application, I did not do proper exception handling and object disposals. Standard code always must follow proper coding standards.

Happy coding.

Sample Project Source

Download source demo files -3 kb

Download source files -5 kb

 
Sign Up to vote for this article
 
About Author
 
ninethsense
Occupation-
Company-
Member Type-Junior
Location-Not Provided
Joined date-21 Jul 2009
Home Page-http://blog.ninethsense.com/
Blog Page-http://blog.ninethsense.com/
 
 
Other popularSectionarticles
    I can see, there is lots of people is discussing about it in MSDN forums, few people wanted to get rid of the Task from the async methods and really want to deal with normal return types, while others just wanted to get rid of the async postfix
    Published Date : 25/Nov/2010
    Are you somewhat confused between Serialization and Marshaling? This writing would break this confusion up, it would give you a basic understanding of the process of Serialization and the process of Marshaling, and how you can get the most out of each.
    Published Date : 10/May/2010
    First, this writing concentrates of and compares between three programming languages, C#, C++/CLI, and ISO/ANSI C++. It discusses 9 rules that every developer should keep in mind while working with constructors, destructors, and finalizers and class hierarchies:
    Published Date : 05/May/2010
    In this article, I will explain three basic terms of C#, such as Call Stack ,Call Site and stack Unwinding
    Published Date : 17/Aug/2010
    In this article, I will discuss about Checked and unchecked keyword and conversions in C#.
    Published Date : 16/Aug/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top