Page d'Accueil

Localiser des enregistrements et leurs valeurs

 

Localiser un enregistrement

Avant d'effectuer n'importe quelle opération sur un enregistrement, vous devez pouvoir le localiser. C'est-à-dire, vous devez pouvoir identifier un enregistrement parmi les divers enregistrements d'un tableau. Pour localiser un enregistrement dans la collection DataTable.Rows, la classe DataRowCollection a une propriété indexée qui est définie comme suit :

public DataRow this[int index] {get;}

Les enregistrements d'un tableau sont stockés dans une liste (appelée DataRowCollection). Le premier enregistrement a un index 0. Le deuxième enregistrement a un index 1, et ainsi de suite. Voici un exemple à utiliser pour recouvrer l'information stockée dans un enregistrement:

DataRow row = this.dtVideos.Rows[2];

Quand vous passez un index à cette propriété, le compilateur vérifierait si l'enregistrement existe. Si un enregistrement avec cet index existe, sa valeur DataRow est produite.

Dans les leçons précédentes, nous avons appris comment localiser une colonne en utilisant la boucle foreach pour visiter les membres d'une collection DataColumnCollection. Comme la classe DataColumnCollection, la classe DataRowCollection applique la méthode GetEnumerator () de l'interface IEnumerable. Ceci signifie que vous pouvez appliquer la boucle foreach à sa collection d'enregistrements pour visiter chaque collection. Comme mentionné déjà, pour accéder à un enregistrement, vous pouvez passer son index à la propriété indexée DataRowCollection, qui produit un objet DataRow. En utilisant ces concepts, vous pouvez accéder aux valeurs d'un tableau. Voici un exemple:

using System;
using System.IO;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static void ShowVideos()
        {
            dsVideos.ReadXml(strDirectory + @"\videos.xml");

            Console.WriteLine("Video Collection");
            Console.WriteLine("================================");
            foreach (DataRow row in tblVideos.Rows)
            {
                foreach (DataColumn col in tblVideos.Columns)
                {
                    Console.WriteLine("{0}", row[col]);
                }
                Console.WriteLine("--------------------------------");
            }
        }

        static int Main(string[] args)
        {
            CreateCollection();
            ShowVideos();

            return 0;
        }
    }
}

Ceci produirait:

Video Collection
================================
GT-682
A Few Good Men
Rob Reiner
138 Minutes
1992
R
--------------------------------
MM-258
Fatal Attraction
Adrian Lyne
120 Minutes
1987
R
--------------------------------
FD-205
Her Alibi
Bruce Beresford
94 Minute
1989
PG-13
--------------------------------
Press any key to continue . . .

La classe DataRow elle-même est équipée d'une propriété ingexée qui vous permet d'accéder à la valeur stockée dans une colonne particulière. Par exemple, vous pouvez utiliser la boucle for pour visiter chaque colonne par son index. Une fois que vous obtenez une colonne, vous pouvez alors utiliser la propriété indexée d'une rangée pour accéder à la valeur stockée sous cette colonne. Voici les exemples:

using System;
using System.IO;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static void ShowVideos()
        {
            dsVideos.ReadXml(strDirectory + @"\videos.xml");

            Console.WriteLine("================================");
            Console.WriteLine("Video Collection");
            Console.WriteLine("================================");
            for (int i = 0; i < tblVideos.Rows.Count; i++)
            {
                DataRow row = tblVideos.Rows[i];
                Console.WriteLine("Shelf #:  {0}", tblVideos.Rows[i]["ShelfNumber"]);
                Console.WriteLine("Title:    {0}", tblVideos.Rows[i]["Title"]);
                Console.WriteLine("Director: {0}", tblVideos.Rows[i]["Director"]);
                Console.WriteLine("Length:   {0}", tblVideos.Rows[i]["Length"]);
                Console.WriteLine("Year:     {0}", tblVideos.Rows[i]["Year"]);
                Console.WriteLine("Rating:   {0}", tblVideos.Rows[i]["Rating"]);
                Console.WriteLine("--------------------------------");
            }
        }

        static int Main(string[] args)
        {
            CreateCollection();
            ShowVideos();

            return 0;
        }
    }
}

Ceci produirait:

================================
Video Collection
================================
Shelf #:  GT-682
Title:    A Few Good Men
Director: Rob Reiner
Length:   138 Minutes
Year:     1992
Rating:   R
--------------------------------
Shelf #:  MM-258
Title:    Fatal Attraction
Director: Adrian Lyne
Length:   120 Minutes
Year:     1987
Rating:   R
--------------------------------
Shelf #:  FD-205
Title:    Her Alibi
Director: Bruce Beresford
Length:   94 Minute
Year:     1989
Rating:   PG-13
--------------------------------
Press any key to continue . . .

En utilisant une quelconque d'entre les techniques précédentes (for ou foreach), si vous indiquez un index qui est soit inférieur 0 ou au delà du nombre d'enregistrements dans le tableau, le compilateur rejetterait une exception IndexOutOfRangeException.

Localiser une valeur

Comme mentionné déjà, un enregistrement est en fait une ou plusieurs valeurs de chacune des colonnes du tableau. Considérez le tableau suivant:

Title Director Length © Year Rating
A Few Good Men Rob Reiner 138 Minutes 1992 R
The Distinguished Gentleman Jonathan Lynn 112 Minutes   R
The Lady Killers Joel Coen & Ethan Coen 104 Minutes   R
Fatal Attraction Adrian Lyne 120 Minutes 1987 R
Her Alibi Bruce Beresford 94 Minutes 1989 PG-13
The Manchurian Candidate Jonathan Demme 129 Minutes 2004 R
 

La chaîne "A Few Good Men" est une valeur de la colonne Titre. De la même manière, 1992 est une valeur de la colonne Année. Dans quelques circonstances, vous devrez localiser une valeur particulière afin d'effectuer une opération dessus. Vous pouvez commencer par localiser l'enregistrement dont vous avez besoin et renvoyez son objet DataRow. Pour connaître le tableau auquel l'enregistrement appartient, accédez à sa propriété DataRow.Table. Cette propriété est déclarée comme suit:

public DataTable Table {get;}

Pour localiser la valeur qu'un enregistrement con tient sous une colonne particulière, la classe DataRow a une propriété indexée qui est prise en charge dans diverses versions (réellement six, mais actuellement nous sommes intéressés par les trois premières seulement). Une des versions de cette propriété utilise la syntaxe suivante :

public object this[string columnName] {get; set;}

Pour utiliser cette propriété, passez le nom de l'objet de la colonne dans les crochets. Voici les exemples:

using System;
using System.IO;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static void ShowVideos()
        {
            dsVideos.ReadXml(strDirectory + @"\videos.xml");

            Console.WriteLine("================================");
            Console.WriteLine("Video Collection");
            Console.WriteLine("================================");
            for (int i = 0; i < tblVideos.Rows.Count; i++)
            {
                DataRow row = tblVideos.Rows[i];
                Console.WriteLine("Shelf #:  {0}",
			tblVideos.Rows[i][colShelfNumber]);
                Console.WriteLine("Title:    {0}", tblVideos.Rows[i][colTitle]);
                Console.WriteLine("Director: {0}", tblVideos.Rows[i][colDirector]);
                Console.WriteLine("Length:   {0}", tblVideos.Rows[i][colLength]);
                Console.WriteLine("Year:     {0}", tblVideos.Rows[i][colYear]);
                Console.WriteLine("Rating:   {0}", tblVideos.Rows[i][colRating]);
                Console.WriteLine("--------------------------------");
            }
        }

        static int Main(string[] args)
        {
            CreateCollection();
            ShowVideos();

            return 0;
        }
    }
}

Au lieu d'utiliser l'index d'une colonne, vous pouvez également localiser une valeur en utilisant le nom de la variable de sa colonne. Pour ce faire, vous pouvez utiliser la syntaxe suivante de la propriété indexée DataRow :

public object this[DataColumn column] {get; set;}

Cette propriété s'attend au nom d'objet de la colonne passée dans ses crochets. Nous avons vu plus tôt comment utiliser cette version de la propriété. Voici les exemples, en utilisant foreach:

using System;
using System.IO;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static void ShowVideos()
        {
            dsVideos.ReadXml(strDirectory + @"\videos.xml");

            Console.WriteLine("================================");
            Console.WriteLine("Video Collection");
            Console.WriteLine("================================");
            foreach (DataRow row in tblVideos.Rows)
            {
                Console.WriteLine("Shelf #:  {0}", row["ShelfNumber"]);
                Console.WriteLine("Title:    {0}", row["Title"]);
                Console.WriteLine("Director: {0}", row["Director"]);
                Console.WriteLine("Length:   {0}", row["Length"]);
                Console.WriteLine("Year:     {0}", row["Year"]);
                Console.WriteLine("Rating:   {0}", row["Rating"]);
                Console.WriteLine("--------------------------------");
            }
        }

        static int Main(string[] args)
        {
            CreateCollection();
            ShowVideos();

            return 0;
        }
    }
}

La troisième option que vous avez est d'identifier la colonne par son index. Pour ce faire, utilisez la syntaxe suivante de la propriété indexée DataRow :

public object this[int columnIndex] {get; set;}

Cette propriété s'attend à l'index de la colonne.

Voici des exemples qui utilisent la boucle for:

using System;
using System.IO;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static void ShowVideos()
        {
            dsVideos.ReadXml(strDirectory + @"\videos.xml");

            Console.WriteLine("================================");
            Console.WriteLine("Video Collection");
            Console.WriteLine("================================");
            for (int i = 0; i < tblVideos.Rows.Count; i++)
            {
                DataRow row = tblVideos.Rows[i];
                Console.WriteLine("Shelf #:  {0}", tblVideos.Rows[i][0]);
                Console.WriteLine("Title:    {0}", tblVideos.Rows[i][1]);
                Console.WriteLine("Director: {0}", tblVideos.Rows[i][2]);
                Console.WriteLine("Length:   {0}", tblVideos.Rows[i][3]);
                Console.WriteLine("Year:     {0}", tblVideos.Rows[i][4]);
                Console.WriteLine("Rating:   {0}", tblVideos.Rows[i][5]);
                Console.WriteLine("--------------------------------");
            }
        }

        static int Main(string[] args)
        {
            CreateCollection();
            ShowVideos();

            return 0;
        }
    }
}

Ou, ici des exemples qui utilisent foreach:

using System;
using System.IO;
using System.Data;

namespace VideoCollection
{
    public static  class Program
    {
        . . . No Change

        static void ShowVideos()
        {
            dsVideos.ReadXml(strDirectory + @"\videos.xml");

            Console.WriteLine("================================");
            Console.WriteLine("Video Collection");
            Console.WriteLine("================================");
            foreach (DataRow row in tblVideos.Rows)
            {
                Console.WriteLine("Shelf #:  {0}", row[0]);
                Console.WriteLine("Title:    {0}", row[1]);
                Console.WriteLine("Director: {0}", row[2]);
                Console.WriteLine("Length:   {0}", row[3]);
                Console.WriteLine("Year:     {0}", row[4]);
                Console.WriteLine("Rating:   {0}", row[5]);
                Console.WriteLine("--------------------------------");
            }
        }

        static int Main(string[] args)
        {
            CreateCollection();
            ShowVideos();

            return 0;
        }
    }
}

Practical Learning Etude pratique: Obtenir les Valeurs d'un Ensemble de données

  1. Accédez au fichier Inventory.cs
  2. Pour permettre à l'utilisateur d'afficher l'inventaire du magasin, changez le fichier comme suit:
     
    using System;
    using System.IO;
    using System.Xml;
    using System.Data;
    
    namespace CollegeParkAutoParts1
    {
        public class Inventory
        {
            // These are the columns of the AutoParts table
            private DataColumn colPartNumber;
            private DataColumn colYear;
            private DataColumn colMake;
            private DataColumn colModel;
            private DataColumn colPartName;
            private DataColumn colPartPrice;
    
            // These are the columns of the StoreItems table
            private DataColumn colItemNumber;
            private DataColumn colItemName;
            private DataColumn colItemPrice;
    
            // These are the table of the CollegeParkAutoParts database
            private DataTable tblAutoParts;
            private DataTable tblStoreItems;
    
            // This is the database
            private DataSet dsStoreItems;
    
            // These are accessory strings
            string strDirectory;
            string strFilename;
    
            // This default constructor is used to create
            // the structures of the tables
            public Inventory()
            {
                colPartNumber = new DataColumn("PartNumber",
                    Type.GetType("System.Int32"));
                colYear = new DataColumn("Year",
                    Type.GetType("System.Int32"));
                colMake = new DataColumn("Make",
                    Type.GetType("System.String"));
                colModel = new DataColumn("Model",
                    Type.GetType("System.String"));
                colPartName = new DataColumn("PartName",
                    Type.GetType("System.String"));
                colPartPrice = new DataColumn("PartPrice",
                    Type.GetType("System.Double"));
    
                tblAutoParts = new DataTable("AutoPart");
                tblAutoParts.Columns.Add(colPartNumber);
                tblAutoParts.Columns.Add(colYear);
                tblAutoParts.Columns.Add(colMake);
                tblAutoParts.Columns.Add(colModel);
                tblAutoParts.Columns.Add(colPartName);
                tblAutoParts.Columns.Add(colPartPrice);
    
                tblStoreItems = new DataTable("StoreItem");
                colItemNumber = new DataColumn("ItemNumber",
                    Type.GetType("System.Int32"));
                colItemName = new DataColumn("ItemName",
                    Type.GetType("System.String"));
                colItemPrice = new DataColumn("ItemPrice",
                    Type.GetType("System.Double"));
               tblStoreItems .Columns.Add(colItemNumber);
               tblStoreItems.Columns.Add(colItemName);
               tblStoreItems.Columns.Add(colItemPrice);
    
                dsStoreItems = new DataSet("StoreItems");
                dsStoreItems.Tables.Add(tblAutoParts);
                dsStoreItems.Tables.Add(tblStoreItems);
    
                // This database will use a folder
                // named College Park Auto Parts
                // and located on the C: drive
                strDirectory = @"C:\College Park Auto Parts";
                strFilename = strDirectory + "\\" + "StoreItems.xml";
    
                DirectoryInfo dirInfo = new DirectoryInfo(strDirectory);
    
                // If the folder doesn't exist already, create it
                if (!dirInfo.Exists)
                    dirInfo.Create();
            }
    
            // This method guides the user in creating a new store item
            public void CreateStoreItem()
            {
                // Accessory variables
                int year = 1960;
                int iPartNumber = 0, iItemNumber = 0;
                double unitPrice = 0.00D;
                string strMake = "Unknown", strModel = "Unknown",
                       strPartName = "N/A", strItemName = "N/A";
                int typeOfItem = 0;
                char ansAdd = 'n';
    
                // If the StoreItems.xml file exists already, then open it
                if (File.Exists(strFilename))
                    dsStoreItems.ReadXml(strFilename);
    
                // This do...while is used in case the user wants to 
                // repeatedly perform these actions
                do
                {
                    try
                    {
                        // Find out what the user wants to do
                        Console.WriteLine("What type of item do you want to add");
                 	    Console.WriteLine(
    			"1. An auto part (for a car or an engine)");
               	    Console.WriteLine(
    			"2. Another type of item, not for a specific car");
                        Console.WriteLine("0. Stop");
                 Console.WriteLine("Enter the following pieces of information");
                        Console.Write("Your Choice: ");
                        typeOfItem = int.Parse(Console.ReadLine());
    
                        // The user wants to add a new car part
                        if (typeOfItem == 1)
                        {
                            // Create a random number of 6 digits
                            Random rndPartNumber = new Random();
                            iPartNumber = rndPartNumber.Next(100000, 999999);
    
                            // Request the information about the car and the part
                            try
                            {
                                Console.Write("Car Year: ");
                                year = int.Parse(Console.ReadLine());
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("Invalid year");
                            }
                            Console.Write("Make (or None if N/A):  ");
                            strMake = Console.ReadLine();
                            Console.Write("Model (or None if N/A): ");
                            strModel = Console.ReadLine();
                            Console.Write("Part Name:              ");
                            strPartName = Console.ReadLine();
    
                            try
                            {
                                Console.Write("Unit Price:             ");
                                unitPrice = double.Parse(Console.ReadLine());
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("Invalid unit price");
                            }
    
                       // Present the user with a summary of the part to be added
                       // This is a safe guard for a console application so that
                       // if the user made a mistake, he or she can dismiss it
                            // instead of adding a part with wrong information
                            Console.WriteLine(
    			    "\nHere is a summary of the part to be added");
                            Console.WriteLine("--------------------------------");
                            Console.WriteLine("Part Number: {0}", iPartNumber);
                            Console.WriteLine("Year:        {0}", year);
                            Console.WriteLine("Make:        {0}", strMake);
                            Console.WriteLine("Model:       {0}", strModel);
                            Console.WriteLine("Part Name:   {0}", strPartName);
                            Console.WriteLine("Unit Price:  {0:C}", unitPrice);
                            Console.WriteLine("--------------------------------");
    
                            Console.Write(
    			  "Are you ready to add it to the database (y/n)? ");
                            ansAdd = char.Parse(Console.ReadLine());
    
                            // If the user has decided to add the part
                            // to the database, then add it
                            if ((ansAdd == 'y') || (ansAdd == 'Y'))
                            {
                                DataRow part = tblAutoParts.NewRow();
                                part["PartNumber"] = iPartNumber;
                                part["Year"] = year;
                                part["Make"] = strMake;
                                part["Model"] = strModel;
                                part["PartName"] = strPartName;
                                part["PartPrice"] = unitPrice;
                                tblAutoParts.Rows.Add(part);
    
                                dsStoreItems.WriteXml(strFilename);
                            }
                            else
                        Console.WriteLine(
    			"The part will not be added to the database");
                        }
                        // For the same logic for other store items
                        // The items in this section can be anything
                        else if (typeOfItem == 2)
                        {
                            Random rndPartNumber = new Random();
                            iItemNumber = rndPartNumber.Next(100000, 999999);
    
                            Console.Write("Item/Description:  ");
                            strItemName = Console.ReadLine();
    
                            try
                            {
                                Console.Write("Unit Price:             ");
                                unitPrice = double.Parse(Console.ReadLine());
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("Invalid unit price");
                            }
                            
                            Console.WriteLine(
    				"\nHere is a summary of the part to be added");
                            Console.WriteLine("--------------------------------");
                            Console.WriteLine("Item Number: {0}", iItemNumber);
                            Console.WriteLine("Name/Descr:  {0}", strItemName);
                            Console.WriteLine("Unit Price:  {0:C}", unitPrice);
                            Console.WriteLine("--------------------------------");
    
                            Console.Write(
    			    "Are you ready to add it to the database (y/n)? ");
                            ansAdd = char.Parse(Console.ReadLine());
    
                            if ((ansAdd == 'y') || (ansAdd == 'Y'))
                            {
                                DataRow item = tblStoreItems.NewRow();
                                item["ItemNumber"] = iItemNumber;
                                item["ItemName"] = strItemName;
                                item["ItemPrice"] = unitPrice;
                                tblStoreItems.Rows.Add(item);
    
                                dsStoreItems.WriteXml(strFilename);
                            }
                            else
                           Console.WriteLine(
    			"The part will not be added to the database");
                        }
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Menu Selection");
                    }
                } while (typeOfItem == 1 || typeOfItem == 2);
            }
    
            // This method is used to display the store inventory of all items
            public void ShowInventory()
            {
                if (File.Exists(strFilename))
                {
                    dsStoreItems.ReadXml(strFilename);
    
                    Console.WriteLine("================================");
                    Console.WriteLine("   College Park Auto Parts");
                    Console.WriteLine("      Store Inventory");
                    Console.WriteLine("        Car Parts");
                    Console.WriteLine("================================");
                    foreach (DataRow part in tblAutoParts.Rows)
                    {
                        Console.WriteLine("Part #:     {0}", part["PartNumber"]);
                        Console.WriteLine("Car Year:   {0}", part["Year"]);
                        Console.WriteLine("Make:       {0}", part["Make"]);
                        Console.WriteLine("Model:      {0}", part["Model"]);
                        Console.WriteLine("Part Name:  {0}", part["PartName"]);
                        Console.WriteLine("Unit Price: {0:C}", part["PartPrice"]);
                        Console.WriteLine("--------------------------------");
                    }
    
                    Console.WriteLine("================================");
                    Console.WriteLine("     Other Store Items");
                    Console.WriteLine("================================");
                    foreach (DataRow item in tblStoreItems.Rows)
                    {
                        Console.WriteLine(
    			"Item #:           {0}", item["ItemNumber"]);
                        Console.WriteLine("Name/Description: {0}",
    			 item["ItemName"]);
                        Console.WriteLine(
    			"Unit Price:       {0:C}", item["ItemPrice"]);
                        Console.WriteLine("--------------------------------");
                    }
                }
            }
        }
    }
  3. Accéde au fichier Program.cs
  4. pour permettre à l'utilisateur de décider de l'action à faire quand l'application lancée, changez le fichier comme suit:
     
    using System;
    
    namespace CollegeParkAutoParts1
    {
        class Program
        {
            static int Main(string[] args)
            {
                char choice = '0';
                Inventory inv = new Inventory();
                
                Console.WriteLine("================================");
                Console.WriteLine("   College Park Auto Parts");
                Console.WriteLine("================================");
                do
                {
                    try
                    {
                        Console.WriteLine("What do you want to do?");
                        Console.WriteLine("1. Add New Store Item");
                        Console.WriteLine("2. View Inventory");
                        Console.WriteLine("0. Quit");
                        Console.Write("Your Selection? ");
                        choice = char.Parse(Console.ReadLine());
    
                        if (choice == '1')
                            inv.CreateStoreItem();
                        else if (choice == '2')
                            inv.ShowInventory();
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Unrecognizable Menu Selection");
                    }
                } while ((choice == '1') || (choice == '2'));
    
                Console.WriteLine();
                return 0;
            }
        }
    }
  5. Executez 'application pour voir le résultat:
     
    =====================================
       College Park Auto Parts
    =====================================
    What do you want to do?
    1. Add New Store Item
    2. View Inventory
    0. Quit
    Your Selection? 2
    ==========================================
       College Park Auto Parts
          Store Inventory
            Car Parts
    ==========================================
    Part #:     299693
    Car Year:   2005
    Make:       Acura
    Model:      NSX 3.0L V6
    Part Name:  Oil Filter
    Unit Price: $8.85
    ------------------------------------------
    Part #:     398747
    Car Year:   2002
    Make:       Audi
    Model:      Quattro 1.8L Turbo
    Part Name:  Clash Bear
    Unit Price: $55.50
    ------------------------------------------
    Part #:     174724
    Car Year:   2002
    Make:       BMW
    Model:      325i 2.5L L6
    Part Name:  Ignition Coil
    Unit Price: $60.85
    ------------------------------------------
    ==========================================
         Other Store Items
    ==========================================
    Item #:           319027
    Name/Description: Soda 2L Bottle
    Unit Price:       $1.75
    ------------------------------------------
    Item #:           865745
    Name/Description: STP Gas Treatment 3-Pack
    Unit Price:       $2.99
    ------------------------------------------
    What do you want to do?
    1. Add New Store Item
    2. View Inventory
    0. Quit
    Your Selection? 0
    
    Press any key to continue . . .
  6. Fermez la fenêtre DOS
 
 

Précédent Copyright © 2007, Yevol Suivant