Curso de ADO.NET e BDP - Parte XVI

Você precisa estar logado para dar um feedback. Clique aqui para efetuar o login
Para efetuar o download você precisa estar logado. Clique aqui para efetuar o login
Confirmar voto
0
 (0)  (0)

Veremos neste artigo como ordenar, filtrar e procurar registros em DataTables de um DataSet.

Acesso a dados no Delphi 8 for .NET

 

Parte XVI – DataSets tipados

Dando continuidade ao nosso curso sobre acesso a dados no Delphi for .NET com ADO.NET e BDP, veremos neste artigo como ordenar, filtrar e procurar registros em DataTables de um DataSet

O que são DataSets tipados?

Quando configuramos um BdpDataAdapter e geramos um DataSet , estamos utilizando para a manipulação dos dados em memória sempre as mesmas classes (DataSet, DataTable etc ). Para acessar nomes de campos, devemos acessar a coleção Columns e referenciar colunas pelo nome (uma string) ou ainda pelo índice. Se precisar recuperar o valor de um campo em um registro, usamos a coleção Rows e novamente acessamos o campo pelo nome. Veja um exemplo:

 

DataSet1.Tables[0].Rows[0][‘NOME_CLIENTE'] := ‘Guinther Pauli';

 

O ADO.NET permite que sejam criadas classes descendentes de DataSet , ou seja, cada tabela é mapeada em uma classe . Isso é muito comum em frameworks de persistência, como o Bold e o ECO. Uma vantagem da abordagem,é claro, é que estaremos trabalhando “mais orientado a objetos” do que baseados em padrões do sistema de BD relacional. Ou seja, a mesma atribuição anterior ficaria algo como:

 

Cliente.Nome := ‘Guinther Pauli';

 

Sendo mais específico, deixaremos de usar coleções para acessar campos da tabela e passamos a tratar uma tabela com um Objeto . Os campos passam a ser Atributos da nova classe, e também podemos incluir operações sobre os dados na mesma classe, como por exemplo, CalcularMedia, SomarPedidos etc. Isso com certeza facilita muito a manutenção da sua aplicação, reforçando ainda princípios básicos da orientação a objetos.

Uma outra vantagem é que você pode tirar vantagem do processo de compilação. Como os campos viram atributos, podemos usar o Code Insight para acessar o nome dos campos. Se usássemos DataSets diretamente, o nome de um campo digitado de forma incorreta só seria detectado em tempo de execução.

Veja um exemplo:

 

 

Criando um DataSet tipado

Inicie uma nova aplicação do tipo Windows Forms Application . Expanda a conexão Employee no Data Explorer e arraste a tabelas Department para o designer. Isso cria um BdpConnection e um BdpDataAdapter . Dê um clique de direita sobre o BdpDataAdapter e escolha a opção Generate Typed DataSet :

 

 

Indique quais as tabelas devem ser usadas para criar a nova classe, nesse caso somente uma:

 

 

Observe que será criado um novo componente no designer, com o nome padrão DataSet11

 

 

Observe que ao projeto são adicionados dois novos arquivos, um arquivo XSD, que é o XML schema representando o DataSet e uma unit, chamada DataSet1Unit , que abriga a classe criada para o DataSet tipado:

 

 

Veja o schema XSD abaixo:

 

 

A listagem a seguir mostra o código gerado para o DataSet tipado, observe que os campos da tabela viraram atributos da classe:

 

//------------------------------------------------------------------------------

// <autogenerated>

//           This code was generated by a tool.

//           Runtime Version: 1.1.4322.573

//

//           Changes to this file may cause incorrect behavior and will be lost if

//           the code is regenerated.

// </autogenerated>

//------------------------------------------------------------------------------

//

// This source code was auto-generated by xsd, Version=1.1.4322.573.

//

unit DataSet1Unit;

interface

uses System.Data,

     System.Xml,

     System.Runtime.Serialization,

     System.Collections,

     System.ComponentModel,

     System.Diagnostics,

     System.Globalization, System.Xml.Schema, System.IO;

type

     [Serializable]

     [System.ComponentModel.DesignerCategoryAttribute('code')]

     [System.Diagnostics.DebuggerStepThrough]

     [System.ComponentModel.ToolboxItem(True)]

     DataSet1 = class (DataSet)

     public

     type

          DEPARTMENTRowChangeEvent = class ;

          DEPARTMENTRowChangeEventHandler = procedure (sender: System.Object; e:

DEPARTMENTRowChangeEvent) of object ;

          DEPARTMENTRow = class ;

          [System.Diagnostics.DebuggerStepThrough]

          DEPARTMENTDataTable = class (DataTable, System.Collections.IEnumerable)

          strict private

               columnDEPT_NO: DataColumn;

               columnDEPARTMENT: DataColumn;

               columnHEAD_DEPT: DataColumn;

               columnMNGR_NO: DataColumn;

               columnBUDGET: DataColumn;

               columnLOCATION: DataColumn;

               columnPHONE_NO: DataColumn;

          public

               DEPARTMENTRowChanged: DEPARTMENTRowChangeEventHandler;                DEPARTMENTRowChanging: DEPARTMENTRowChangeEventHandler;

               DEPARTMENTRowDeleted: DEPARTMENTRowChangeEventHandler;

              DEPARTMENTRowDeleting: DEPARTMENTRowChangeEventHandler;

          private

               constructor Create; overload ;

               constructor Create(table: DataTable); overload ;

          public

              function get_Count: Integer;

         private

              function get_DEPT_NOColumn: DataColumn;

              function get_DEPARTMENTColumn: DataColumn;

              function get_HEAD_DEPTColumn: DataColumn;

              function get_MNGR_NOColumn: DataColumn;

              function get_BUDGETColumn: DataColumn;

              function get_LOCATIONColumn: DataColumn;

              function get_PHONE_NOColumn: DataColumn;

         public

             function get_Item( index : Integer): DEPARTMENTRow;

             [System.ComponentModel.Browsable(False)]

            property Count: Integer read get_Count;

         private

            property DEPT_NOColumn: DataColumn read get_DEPT_NOColumn;

            property DEPARTMENTColumn: DataColumn read get_DEPARTMENTColumn;

            property HEAD_DEPTColumn: DataColumn read get_HEAD_DEPTColumn;

            property MNGR_NOColumn: DataColumn read get_MNGR_NOColumn;

            property BUDGETColumn: DataColumn read get_BUDGETColumn;

            property LOCATIONColumn: DataColumn read get_LOCATIONColumn;

            property PHONE_NOColumn: DataColumn read get_PHONE_NOColumn;

         public

            property Item[ index : Integer]: DEPARTMENTRow read get_Item;

            procedure AddDEPARTMENTRow(row: DEPARTMENTRow); overload ;

            function AddDEPARTMENTRow(DEPT_NO: string ; DEPARTMENT: string ; HEAD_DEPT: string ; MNGR_NO: SmallInt; BUDGET: System.Double; LOCATION: string ; PHONE_NO: string ): EPARTMENTRow; overload ;

            function FindByDEPT_NODEPARTMENT(DEPT_NO: string ; DEPARTMENT: string ): DEPARTMENTRow;

            function GetEnumerator: System.Collections.IEnumerator;

            function Clone: DataTable; override ;

       strict protected

            function CreateInstance: DataTable; override ;

       private

            procedure InitVars;

        strict private

            procedure InitClass;

        public

            function NewDEPARTMENTRow: DEPARTMENTRow;

        strict protected

            function NewRowFromBuilder(builder: DataRowBuilder): DataRow; override ;

            function GetRowType: System.Type; override ;

           procedure OnRowChanged(e: DataRowChangeEventArgs); override ;

           procedure OnRowChanging(e: DataRowChangeEventArgs); override ;

           procedure OnRowDeleted(e: DataRowChangeEventArgs); override ;

           procedure OnRowDeleting(e: DataRowChangeEventArgs); override ;

        public

           procedure RemoveDEPARTMENTRow(row: DEPARTMENTRow);

       end ;

            [System.Diagnostics.DebuggerStepThrough]

            DEPARTMENTRow = class (DataRow)

        strict private

            tableDEPARTMENT: DEPARTMENTDataTable;

        private

            constructor Create(rb: DataRowBuilder);

        public

            function get_DEPT_NO: string ;

            function get_DEPARTMENT: string ;

           function get_HEAD_DEPT: string ;

           function get_MNGR_NO: SmallInt;

           function get_BUDGET: System.Double;

           function get_LOCATION: string ;

           function get_PHONE_NO: string ;

           procedure set _DEPT_NO(Value: string );

           procedure set _DEPARTMENT(Value: string );

           procedure set _HEAD_DEPT(Value: string );

           procedure set _MNGR_NO(Value: SmallInt);

           procedure set _BUDGET(Value: System.Double);

           procedure set _LOCATION(Value: string );

           procedure set _PHONE_NO(Value: string );

           property DEPT_NO: string read get_DEPT_NO write set _DEPT_NO;

           property DEPARTMENT: string read get_DEPARTMENT write set _DEPARTMENT;

           property HEAD_DEPT: string read get_HEAD_DEPT write set _HEAD_DEPT;

           property MNGR_NO: SmallInt read get_MNGR_NO write set _MNGR_NO;

           property BUDGET: System.Double read get_BUDGET write set _BUDGET;

           property LOCATION: string read get_LOCATION write set _LOCATION;

           property PHONE_NO: string read get_PHONE_NO write set _PHONE_NO;

           function IsHEAD_DEPTNull: Boolean;

           procedure SetHEAD_DEPTNull;

           function IsMNGR_NONull: Boolean;

           procedure SetMNGR_NONull;

           function IsBUDGETNull: Boolean;

           procedure SetBUDGETNull;

           function IsLOCATIONNull: Boolean;

           procedure SetLOCATIONNull;

           function IsPHONE_NONull: Boolean;

           procedure SetPHONE_NONull;

       end ;

       [System.Diagnostics.DebuggerStepThrough]

       DEPARTMENTRowChangeEvent = class (EventArgs)

       strict private

            eventRow: DEPARTMENTRow;

            eventAction: DataRowAction;

        public

             constructor Create(row: DEPARTMENTRow; action: DataRowAction);

             function get_Row: DEPARTMENTRow;

             function get_Action: DataRowAction;

             property Row: DEPARTMENTRow read get_Row;

             property Action: DataRowAction read get_Action;

       end ;

       strict private

             tableDEPARTMENT: DEPARTMENTDataTable;

        public

            constructor Create; overload ;

        strict protected

            constructor Create(info: SerializationInfo; context: StreamingContext); overload ;

        public

            function get_DEPARTMENT: DEPARTMENTDataTable;            [System.ComponentModel.Browsable(False)]

       [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Content)]              property DEPARTMENT: DEPARTMENTDataTable read get_DEPARTMENT;

             function Clone: DataSet; override ;

       strict protected

            function ShouldSerializeTables: Boolean; override ;

            function ShouldSerializeRelations: Boolean; override ;

           procedure ReadXmlSerializable(reader: XmlReader); override ;

           function GetSchemaSerializable: System.Xml.Schema.XmlSchema; override ;

       private

           procedure InitVars;

       strict private

           procedure InitClass;

           function ShouldSerializeDEPARTMENT: Boolean;

           procedure SchemaChanged(sender: System.Object; e: System.ComponentModel.CollectionChangeEventArgs);

       end ;

        implementation

        {$AUTOBOX ON}

        {$HINTS OFF}

        {$WARNINGS OFF}

        [assembly: RuntimeRequired(TypeOf(DataSet1))]

        constructor DataSet1.DEPARTMENTDataTable.Create;

        begin

           inherited Create('DEPARTMENT');

           Self.InitClass;

        end ;

        constructor DataSet1.DEPARTMENTDataTable.Create(table: DataTable);

        begin

            inherited Create(table.TableName);

            if (table.CaseSensitive <> table.DataSet.CaseSensitive) then

                 Self.CaseSensitive := table.CaseSensitive;

            if (table.Locale.ToString <> table.DataSet.Locale.ToString) then

                 Self.Locale := table.Locale;

            if (table.Namespace <> table.DataSet.Namespace) then

            Self.Namespace := table.Namespace;

            Self.Prefix := table.Prefix;

            Self.MinimumCapacity := table.MinimumCapacity;

            Self.DisplayExpression := table.DisplayExpression;

        end ;

        function DataSet1.DEPARTMENTDataTable.get_Count: Integer;

        begin

              Result := Self.Rows.Count;

        end ;

        function DataSet1.DEPARTMENTDataTable.get_DEPT_NOColumn: DataColumn;

        begin

              Result := Self.columnDEPT_NO;

        end ;

        function DataSet1.DEPARTMENTDataTable.get_DEPARTMENTColumn: DataColumn;

        begin

              Result := Self.columnDEPARTMENT;

        end ;

        function DataSet1.DEPARTMENTDataTable.get_HEAD_DEPTColumn: DataColumn;

        begin

               Result := Self.columnHEAD_DEPT;

        end ;

        function DataSet1.DEPARTMENTDataTable.get_MNGR_NOColumn: DataColumn;         

        begin

               Result := Self.columnMNGR_NO;

        end ;

        function DataSet1.DEPARTMENTDataTable.get_BUDGETColumn: DataColumn;

        begin

              Result := Self.columnBUDGET;

        end ;

         function DataSet1.DEPARTMENTDataTable.get_LOCATIONColumn: DataColumn;

         begin

                Result := Self.columnLOCATION;

         end ;

         function DataSet1.DEPARTMENTDataTable.get_PHONE_NOColumn: DataColumn;

         begin

                Result := Self.columnPHONE_NO;

        end ;

         function DataSet1.DEPARTMENTDataTable.get_Item( index : Integer): DEPARTMENTRow;

         begin

               Result := (DEPARTMENTRow(Self.Rows[ index ]));

         end ;

         procedure DataSet1.DEPARTMENTDataTable.AddDEPARTMENTRow(row: DEPARTMENTRow);

         begin

                Self.Rows.Add(row);

         end ;

         function DataSet1.DEPARTMENTDataTable.AddDEPARTMENTRow(DEPT_NO: string ; DEPARTMENT: string ; HEAD_DEPT: string ; MNGR_NO: SmallInt; BUDGET: System.Double; LOCATION: string ; PHONE_NO: string ): DEPARTMENTRow;

        type

               TArrayOfSystem_Object = array of System.Object;

        var

               rowDEPARTMENTRow: DEPARTMENTRow;

        begin

               rowDEPARTMENTRow := (DEPARTMENTRow(Self.NewRow));                rowDEPARTMENTRow.ItemArray := TArrayOfSystem_Object.Create(DEPT_NO, DEPARTMENT, HEAD_DEPT, MNGR_NO, BUDGET, LOCATION, PHONE_NO);                Self.Rows.Add(rowDEPARTMENTRow);

                Result := rowDEPARTMENTRow;

         end ;

         function DataSet1.DEPARTMENTDataTable.FindByDEPT_NODEPARTMENT(DEPT_NO: string; DEPARTMENT: string ): DEPARTMENTRow;

         type

               TArrayOfSystem_Object = array of System.Object;

         begin

               Result := (DEPARTMENTRow(Self.Rows.Find(TArrayOfSystem_Object.Create(DEPT_NO, DEPARTMENT))));

         end ;

         function DataSet1.DEPARTMENTDataTable.GetEnumerator: System.Collections.IEnumerator;

         begin

                Result := Self.Rows.GetEnumerator;

         end ;

          function DataSet1.DEPARTMENTDataTable.Clone: DataTable;

          var

                cln: DEPARTMENTDataTable;

          begin

                 cln := (DEPARTMENTDataTable( inherited Clone));

                 cln.InitVars;

                 Result := cln;

          end ;

          function DataSet1.DEPARTMENTDataTable.CreateInstance: DataTable;

          begin

                 Result := DEPARTMENTDataTable.Create;

          end ;

          procedure DataSet1.DEPARTMENTDataTable.InitVars;

          begin

                 Self.columnDEPT_NO := Self.Columns['DEPT_NO'];

                 Self.columnDEPARTMENT := Self.Columns['DEPARTMENT'];

                 Self.columnHEAD_DEPT := Self.Columns['HEAD_DEPT'];

                 Self.columnMNGR_NO := Self.Columns['MNGR_NO'];

                 Self.columnBUDGET := Self.Columns['BUDGET'];

                 Self.columnLOCATION := Self.Columns['LOCATION'];

                 Self.columnPHONE_NO := Self.Columns['PHONE_NO'];

          end ;

          procedure DataSet1.DEPARTMENTDataTable.InitClass;

          type

                 TArrayOfDataColumn = array of DataColumn;

          begin

                Self.columnDEPT_NO := DataColumn.Create('DEPT_NO', TypeOf( string ), nil ,                      System.Data.MappingType.Element);

                Self.Columns.Add(Self.columnDEPT_NO);

                Self.columnDEPARTMENT := DataColumn.Create('DEPARTMENT', TypeOf( string ), nil ,

                     System.Data.MappingType.Element);

                Self.Columns.Add(Self.columnDEPARTMENT);

                Self.columnHEAD_DEPT := DataColumn.Create('HEAD_DEPT', TypeOf( string ), nil ,

                     System.Data.MappingType.Element);

                Self.Columns.Add(Self.columnHEAD_DEPT);

                Self.columnMNGR_NO := DataColumn.Create('MNGR_NO', TypeOf(SmallInt), nil ,                      System.Data.MappingType.Element);

                Self.Columns.Add(Self.columnMNGR_NO); Self.columnBUDGET := DataColumn.Create('BUDGET', TypeOf(System.Double), nil , System.Data.MappingType.Element);

               Self.Columns.Add(Self.columnBUDGET);

               Self.columnLOCATION := DataColumn.Create('LOCATION', TypeOf( string ), nil ,                      System.Data.MappingType.Element);

               Self.Columns.Add(Self.columnLOCATION); Self.columnPHONE_NO := DataColumn.Create('PHONE_NO', TypeOf( string ), nil , System.Data.MappingType.Element);

               Self.Columns.Add(Self.columnPHONE_NO);

               Self.Constraints.Add(UniqueConstraint.Create('Constraint2',

TArrayOfDataColumn.Create(Self.columnDEPT_NO,

               Self.columnDEPARTMENT), True));                Self.Constraints.Add(UniqueConstraint.Create('Constraint1', TArrayOfDataColumn.Create(Self.columnDEPARTMENT),

                     False));

               Self.columnDEPT_NO.AllowDBNull := False;

               Self.columnDEPARTMENT.AllowDBNull := False;

               Self.columnDEPARTMENT.Unique := True;

          end ;

          function DataSet1.DEPARTMENTDataTable.NewDEPARTMENTRow: DEPARTMENTRow;

          begin

                Result := (DEPARTMENTRow(Self.NewRow));

          end ;

          function DataSet1.DEPARTMENTDataTable.NewRowFromBuilder(builder: DataRowBuilder):

DataRow;

         begin

               Result := DEPARTMENTRow.Create(builder);

         end ;

         function DataSet1.DEPARTMENTDataTable.GetRowType: System.Type;

         begin

                Result := TypeOf(DEPARTMENTRow);

         end ;

         procedure DataSet1.DEPARTMENTDataTable.OnRowChanged(e: DataRowChangeEventArgs);

         begin

                inherited OnRowChanged(e);

                if (Assigned(Self.DEPARTMENTRowChanged)) then

                    Self.DEPARTMENTRowChanged(Self,

DEPARTMENTRowChangeEvent.Create((DEPARTMENTRow(e.Row)), e.Action));

         end ;

         procedure DataSet1.DEPARTMENTDataTable.OnRowChanging(e: DataRowChangeEventArgs);

         begin

                inherited OnRowChanging(e);

                if (Assigned(Self.DEPARTMENTRowChanging)) then

                     Self.DEPARTMENTRowChanging(Self, DEPARTMENTRowChangeEvent.Create((DEPARTMENTRow(e.Row)), e.Action));

         end ;

         procedure DataSet1.DEPARTMENTDataTable.OnRowDeleted(e: DataRowChangeEventArgs);

         begin

                inherited OnRowDeleted(e);

                if (Assigned(Self.DEPARTMENTRowDeleted)) then

                     Self.DEPARTMENTRowDeleted(Self, DEPARTMENTRowChangeEvent.Create((DEPARTMENTRow(e.Row)), e.Action));

         end ;

         procedure DataSet1.DEPARTMENTDataTable.OnRowDeleting(e: DataRowChangeEventArgs);

         begin

                inherited OnRowDeleting(e);

                if (Assigned(Self.DEPARTMENTRowDeleting)) then

                      Self.DEPARTMENTRowDeleting(Self, DEPARTMENTRowChangeEvent.Create((DEPARTMENTRow(e.Row)), e.Action));

         end ;

         procedure DataSet1.DEPARTMENTDataTable.RemoveDEPARTMENTRow(row: DEPARTMENTRow);

         begin

               Self.Rows.Remove(row);

         end ;

         constructor DataSet1.DEPARTMENTRow.Create(rb: DataRowBuilder);

         begin

                inherited Create(rb);

                Self.tableDEPARTMENT := (DEPARTMENTDataTable(Self.Table));

        end ;

        function DataSet1.DEPARTMENTRow.get_DEPT_NO: string ;

        begin

              Result := ( string (Self[Self.tableDEPARTMENT.DEPT_NOColumn]));

        end ;

        function DataSet1.DEPARTMENTRow.get_DEPARTMENT: string ;

        begin

              Result := ( string (Self[Self.tableDEPARTMENT.DEPARTMENTColumn]));

        end ;

        function DataSet1.DEPARTMENTRow.get_HEAD_DEPT: string ;

        begin

              try

                 Result := ( string (Self[Self.tableDEPARTMENT.HEAD_DEPTColumn]));

                 Exit;

              except

                  on e: InvalidCastException do raise StrongTypingException.Create('Cannot get value because it is DBNull.', e);

              end ;

       end ;

       function DataSet1.DEPARTMENTRow.get_MNGR_NO: SmallInt;

       begin

             try

                Result := (SmallInt(Self[Self.tableDEPARTMENT.MNGR_NOColumn]));

                Exit;

             except

                on e: InvalidCastException do raise StrongTypingException.Create('Cannot get value because it is DBNull.', e);

             end ;

        end ;

        function DataSet1.DEPARTMENTRow.get_BUDGET: System.Double;

        begin

               try

                  Result := (System.Double(Self[Self.tableDEPARTMENT.BUDGETColumn]));

                  Exit;

               except

                   on e: InvalidCastException do raise StrongTypingException.Create('Cannot get value because it is DBNull.', e);

               end ;

        end ;

        function DataSet1.DEPARTMENTRow.get_LOCATION: string ;

        begin

              try

                Result := ( string (Self[Self.tableDEPARTMENT.LOCATIONColumn]));

                Exit;

              except

                 on e: InvalidCastException do raise StrongTypingException.Create('Cannot get value because it is DBNull.', e);

              end ;

         end ;

         function DataSet1.DEPARTMENTRow.get_PHONE_NO: string ;

         begin

                try

                   Result := ( string (Self[Self.tableDEPARTMENT.PHONE_NOColumn]));

                   Exit;

                except

                   on e: InvalidCastException do raise StrongTypingException.Create('Cannot get value because it is DBNull.', e);

                end ;

          end ;

          procedure DataSet1.DEPARTMENTRow. set _DEPT_NO(Value: string );

          begin

                 Self[Self.tableDEPARTMENT.DEPT_NOColumn] := Value;

          end ;

          procedure DataSet1.DEPARTMENTRow. set _DEPARTMENT(Value: string );

          begin

                Self[Self.tableDEPARTMENT.DEPARTMENTColumn] := Value;

          end ;

          procedure DataSet1.DEPARTMENTRow. set _HEAD_DEPT(Value: string );

          begin

                Self[Self.tableDEPARTMENT.HEAD_DEPTColumn] := Value;

          end ;

          procedure DataSet1.DEPARTMENTRow. set _MNGR_NO(Value: SmallInt);

          begin

                 Self[Self.tableDEPARTMENT.MNGR_NOColumn] := Value;

          end ;

          procedure DataSet1.DEPARTMENTRow. set _BUDGET(Value: System.Double);

          begin

                 Self[Self.tableDEPARTMENT.BUDGETColumn] := Value;

          end ;

          procedure DataSet1.DEPARTMENTRow. set _LOCATION(Value: string );

          begin

                 Self[Self.tableDEPARTMENT.LOCATIONColumn] := Value;

          end ;

          procedure DataSet1.DEPARTMENTRow. set _PHONE_NO(Value: string );

          begin

                Self[Self.tableDEPARTMENT.PHONE_NOColumn] := Value;

          end ;

          function DataSet1.DEPARTMENTRow.IsHEAD_DEPTNull: Boolean;

          begin

               Result := Self.IsNull(Self.tableDEPARTMENT.HEAD_DEPTColumn);

          end ;

           procedure DataSet1.DEPARTMENTRow.SetHEAD_DEPTNull;

           begin

                 Self[Self.tableDEPARTMENT.HEAD_DEPTColumn] := System.Convert.DBNull;

           end ;

           function DataSet1.DEPARTMENTRow.IsMNGR_NONull: Boolean;

           begin

                 Result := Self.IsNull(Self.tableDEPARTMENT.MNGR_NOColumn);

          end ;

          procedure DataSet1.DEPARTMENTRow.SetMNGR_NONull;

          begin

                Self[Self.tableDEPARTMENT.MNGR_NOColumn] := System.Convert.DBNull;

          end ;

          function DataSet1.DEPARTMENTRow.IsBUDGETNull: Boolean;

          begin

                Result := Self.IsNull(Self.tableDEPARTMENT.BUDGETColumn);

          end ;

          procedure DataSet1.DEPARTMENTRow.SetBUDGETNull;

          begin

                Self[Self.tableDEPARTMENT.BUDGETColumn] := System.Convert.DBNull;

          end ;

          function DataSet1.DEPARTMENTRow.IsLOCATIONNull: Boolean;

          begin

                Result := Self.IsNull(Self.tableDEPARTMENT.LOCATIONColumn);

          end ;

          procedure DataSet1.DEPARTMENTRow.SetLOCATIONNull;

           begin

                 Self[Self.tableDEPARTMENT.LOCATIONColumn] := System.Convert.DBNull;

          end ;

          function DataSet1.DEPARTMENTRow.IsPHONE_NONull: Boolean;

          begin

                Result := Self.IsNull(Self.tableDEPARTMENT.PHONE_NOColumn);

          end ;

          procedure DataSet1.DEPARTMENTRow.SetPHONE_NONull;

          begin

                Self[Self.tableDEPARTMENT.PHONE_NOColumn] := System.Convert.DBNull;

          end ;

          constructor DataSet1.DEPARTMENTRowChangeEvent.Create(row: DEPARTMENTRow; action: DataRowAction);

          begin

                 inherited Create;

                 Self.eventRow := row;

                 Self.eventAction := action;

          end ;

          function DataSet1.DEPARTMENTRowChangeEvent.get_Row: DEPARTMENTRow;

          begin

                Result := Self.eventRow;

         end ;

         function DataSet1.DEPARTMENTRowChangeEvent.get_Action: DataRowAction;

         begin

               Result := Self.eventAction;

        end ;

        constructor DataSet1.Create;

        var

            schemaChangedHandler: System.ComponentModel.CollectionChangeEventHandler;

        begin

              inherited Create;

              Self.InitClass;

              schemaChangedHandler := Self.SchemaChanged;

              Include(Self.Tables.CollectionChanged, schemaChangedHandler);

              Include(Self.Relations.CollectionChanged, schemaChangedHandler);

        end ;

        constructor DataSet1.Create(info: SerializationInfo; context: StreamingContext);

        var

            schemaChangedHandler: System.ComponentModel.CollectionChangeEventHandler;

            ds: DataSet;

            strSchema: string ;

        begin

              inherited Create;

              strSchema := ( string (info.GetValue('XmlSchema', TypeOf( string ))));

              if (strSchema <> nil ) then

              begin

                     ds := DataSet.Create;                      ds.ReadXmlSchema(XmlTextReader.Create(System.IO.StringReader.Create(strSchema)));

                     if (ds.Tables['DEPARTMENT'] <> nil ) then                          Self.Tables.Add(DEPARTMENTDataTable.Create(ds.Tables['DEPARTMENT']));                     Self.DataSetName := ds.DataSetName;

                    Self.Prefix := ds.Prefix;

                    Self.Namespace := ds.Namespace;

                    Self.Locale := ds.Locale; Self.CaseSensitive := ds.CaseSensitive;

                    Self.EnforceConstraints := ds.EnforceConstraints;

                    Self.Merge(ds, False, System.Data.MissingSchemaAction.Add);

                    Self.InitVars;

              end

              else

                    Self.InitClass;

               Self.GetSerializationData(info, context);

               schemaChangedHandler := Self.SchemaChanged;

               Include(Self.Tables.CollectionChanged, schemaChangedHandler);

               Include(Self.Relations.CollectionChanged, schemaChangedHandler);

        end ;

        function DataSet1.get_DEPARTMENT: DEPARTMENTDataTable;

        begin

              Result := Self.tableDEPARTMENT;

        end ;

        function DataSet1.Clone: DataSet;

        var

              cln: DataSet1;

        begin

               cln := (DataSet1( inherited Clone));

               cln.InitVars;

               Result := cln;

        end ;

        function DataSet1.ShouldSerializeTables: Boolean;

        begin

              Result := False;

        end ;

        function DataSet1.ShouldSerializeRelations: Boolean;

        begin

              Result := False;

       end ;

       procedure DataSet1.ReadXmlSerializable(reader: XmlReader);

       var

             ds: DataSet;

       begin

             Self.Reset;

             ds := DataSet.Create;

             ds.ReadXml(reader);

             if (ds.Tables['DEPARTMENT'] <> nil ) then

                 Self.Tables.Add(DEPARTMENTDataTable.Create(ds.Tables['DEPARTMENT']));              Self.DataSetName := ds.DataSetName;

             Self.Prefix := ds.Prefix;

             Self.Namespace := ds.Namespace;

             Self.Locale := ds.Locale;

             Self.CaseSensitive := ds.CaseSensitive;

             Self.EnforceConstraints := ds.EnforceConstraints;

             Self.Merge(ds, False, System.Data.MissingSchemaAction.Add);

             Self.InitVars;

       end ;

       function DataSet1.GetSchemaSerializable: System.Xml.Schema.XmlSchema;

      var

            stream: System.IO.MemoryStream;

      begin

            stream := System.IO.MemoryStream.Create; Self.WriteXmlSchema(XmlTextWriter.Create(stream, nil ));

            stream.Position := 0;

           Result := System.Xml.Schema.XmlSchema.Read(XmlTextReader.Create(stream), nil );

      end ;

      procedure DataSet1.InitVars;

      begin

            Self.tableDEPARTMENT := (DEPARTMENTDataTable(Self.Tables['DEPARTMENT']));

             if (Self.tableDEPARTMENT <> nil ) then

                 Self.tableDEPARTMENT.InitVars;

       end ;

      procedure DataSet1.InitClass;

      begin

            Self.DataSetName := 'DataSet1';

            Self.Prefix := '';

            Self.Namespace := 'http://www.changeme.now/DataSet1.xsd';

            Self.Locale := System.Globalization.CultureInfo.Create('pt-BR');

            Self.CaseSensitive := False;

            Self.EnforceConstraints := True;

            Self.tableDEPARTMENT := DEPARTMENTDataTable.Create;

            Self.Tables.Add(Self.tableDEPARTMENT);

       end ;

       function DataSet1.ShouldSerializeDEPARTMENT: Boolean;

       begin

             Result := False;

        end ;

        procedure DataSet1.SchemaChanged(sender: System.Object; e:        System.ComponentModel.CollectionChangeEventArgs);

       begin

             if (e.Action = System.ComponentModel.CollectionChangeAction.Remove) then

                  Self.InitVars;

      end ;

 

      end .

Usando o novo DataSet tipado

Coloque no formulário principal um DataGrid e aponte seu DataSource para DataSet11.DEPARTMENT . Coloque um Button e no seu evento Click digite:

 

procedure TWinForm1.Button1_Click(sender: System.Object; e: System.EventArgs);

var

  Dep: DataSet1Unit.DataSet1.DEPARTMENTRow;

begin

   Dep := DataSet11.DEPARTMENT.NewDEPARTMENTRow;

   Dep.DEPT_NO := '1000';

   Dep.DEPARTMENT := 'Isso é bem mais OO!';

   Dep.LOCATION := 'Delphi 2005 rocks!';      

   DataSet11.DEPARTMENT.AddDEPARTMENTRow(Dep);

end ;

 

Aqui usamos os novos tipos declarados na unit para o DataSet gerado, adicionamos um Row e configuramos os valores para seus campos, e a seguir incluímos no DataTable Department do Datset .

Execute e teste a aplicação. Veja abaixo o novo registro inserido:

 

 

Download

Você pode fazer download de todos os exemplos deste curso a partir do endereço

http://cc.borland.com/cc/ccweb.exe/author?authorid=222668

Leia todos artigos da série

 
Você precisa estar logado para dar um feedback. Clique aqui para efetuar o login
Receba nossas novidades
Ficou com alguma dúvida?