SQL C#

Using SQL Row Filters

This C# program demonstrates how to use row filters in an SQL table in a database for Microsoft SQL in C#.

Program.cs

using System;
using System.Data;
using System.Data.SqlClient;

namespace UsingRowFilters {
    class Program {
        static void Main(string[] args) {
            PrintFilteredRows("apostles");
        }

        static void PrintFilteredRows(string sTableName) {
            // The using block ensures that the connection is closed when it exits this block.
            using (SqlConnection qConnection = new SqlConnection(
                    @"Server=localhost\SQLEXPRESS01;Database=catholic;Trusted_Connection=True;")) {
                qConnection.Open();
                DataSet qDataSet = new DataSet("catholic");
                using (SqlDataAdapter qAdapter =
                        new SqlDataAdapter("SELECT * FROM " + sTableName, qConnection)) {
                    qAdapter.Fill(qDataSet, sTableName);
                }
                DataTable qDataTable = qDataSet.Tables[sTableName];
                DataView qDataView = new DataView(qDataTable);

                /// This is an array of the defined states.
                string[] saRowFilters = new string[] {
                    "name = 'Peter'",
                    "name < 'Peter'",
                    "name > 'a'",
                    "symbol > 'K'",
                    "symbol < 't'"
                };

                // Run through the array of row states and apply a filter for each one.
                foreach (string eRowFilter in saRowFilters) {
                    Console.WriteLine(eRowFilter);
                    Console.WriteLine("----------------------------------------");
                    qDataView.RowFilter = eRowFilter;
                    // Iterate over the rows in the data table
                    for (int i = 0; i < qDataView.Count; i++) {
                        foreach (object qItem in qDataView[i].Row.ItemArray) {
                            Console.Write(String.Format("{0,-20}", qItem));
                        }
                        Console.WriteLine();
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}
 

Output

name = 'Peter'
----------------------------------------
Peter               Keys

name < 'Peter'
----------------------------------------
John                Chalice
Andrew              Transverse Cross

name > 'a'
----------------------------------------
John                Chalice
Andrew              Transverse Cross
Peter               Keys

symbol > 'K'
----------------------------------------
Andrew              Transverse Cross
Peter               Keys

symbol < 't'
----------------------------------------
John                Chalice
Peter               Keys

Press any key to continue . . .
 

Tables

Tables
 

Apostles Table

Apostles Table
 
 

© 2007–2025 XoaX.net LLC. All rights reserved.