Wednesday, May 1, 2013

How to Select from Data Table in C#

DataTable Object has a Select Method which acts like Where in SQL Server. So if you want to write filter query you write the column name directly without Where and the filter expression you want.

I made a simple example that creates a DataTable and fill it with some data and use Select method:

DataTable dt = new DataTable("MyDataTable");
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

for (int i = 0; i < 10; i++)
{
    DataRow dr = dt.NewRow();
    dr["ID"] = i + 1;
    dr["Name"] = "Name " + (i + 1).ToString();

    dt.Rows.Add(dr);
}

DataRow[] rows = dt.Select("ID = 3");