Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Escribir un Valor en un Edit y Buscarlo en Un archivo TXT (https://www.clubdelphi.com/foros/showthread.php?t=82567)

hondaalberto 19-03-2013 20:41:00

Escribir un Valor en un Edit y Buscarlo en Un archivo TXT
 
Buenas tardes Amigo tengo la Siguiente Inquietud.

Tengo un archivo de Texto que contiene muchas lineas y cada valor separado por este simbolo "|", Necesito escribir en un Edit el número que aparece al principio "00100235701" Y mostrar en un otros edits los demas datos que pertenecen a este número:

Ejemplo:

Edit1= JUAN PEREZ PEREZ
EDIT2= SERVICIOS PERSONALES EN GENERAL
......

Ejemplo de la Estructura del Archivo, Todos esos datos estan en una línea en el Archivo.:

00100235701|JUAN PEREZ PEREZ||SERVICIOS PERSONALES EN GENERA| | | | |25/0/1999|ACTIVO|NORMAL

Muchas Gracias por anticipado por su valiosa ayuda.

TOPX 19-03-2013 20:46:51

Buenas tardes,

Por favor revise la respuesta #4 del siguiente hilo:
-

nlsgarcia 20-03-2013 03:13:45

hondaalberto,

Cita:

Empezado por hondaalberto
...Tengo un archivo de Texto que contiene muchas lineas y cada valor separado por este simbolo "|"...

Revisa este código:
Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, StrUtils;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Button1: TButton;
    ListBox1: TListBox;
    Edit4: TEdit;
    procedure Button1Click(Sender: TObject);
    procedure ListBox1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
   ListBox1.Items.LoadFromFile('Data.txt');
end;

procedure TForm1.ListBox1Click(Sender: TObject);
var
   StrList : TStringList;
   i,j,p : Integer;
   offset : Integer;
   Data : string;

begin

   StrList := TStringList.Create;

   for i := 0 to ListBox1.Count -1 do
      if ListBox1.Selected[i] then
         begin
            offset := 1;
            Data := ListBox1.Items.Strings[i]+'|';
            for j := 1 to Length(Data) do
            begin
               if  Data[j] = '|' then
               begin
                  p := PosEx('|',Data,offset);
                  StrList.Add(Copy(Data,offset,p-offset));
                  offset := p+1;
               end;
            end;
            Edit1.Text := StrList[0];
            Edit2.Text := StrList[1];
            Edit3.Text := StrList[2];
            Edit4.Text := StrList[3];
            Break;
         end;

   StrList.Free;

end;

end.
El código anterior lee un archivo TXT en el cual los datos son separados con el carácter "|" en un control TListBox y al pulsar cada item del control (Registros del archivo TXT) los campos son separados y cargados en una variable TStringList la cual almacenara todos los campos del registro para su posterior procesamiento en controles TEdit.

Para efectos del ejemplo el archivo tiene solo 4 campos por registro, los cuales son extensibles según se requiera:
Cita:

111111|Nombre1 Apellido1|Departamento Empresa 1|01/01/2013
222222|Nombre2 Apellido2|Departamento Empresa 2|02/02/2013
333333|Nombre3 Apellido3|Departamento Empresa 3|03/03/2013
El código y el archivo de prueba están disponibles en el link : http://terawiki.clubdelphi.com/Delph...ArchivoTXT.rar

Espero sea útil :)

Nelson.

ecfisa 20-03-2013 07:21:06

Hola.

Otra alternativa para obtener un determinado campo:
Código Delphi [-]
function GetTextField(const SearchedText: string; SList: TStrings;
  const InxRetField: Integer; const Sep: Char): string;
var
  Aux  : TStrings;
  i    : Integer;
  Found: Boolean;
begin
  Result := '';
  i      := 0;
  Found  := False;
  while not Found and (i < SList.Count) do
  begin
    Aux := TStringList.Create;
    try
      Aux.Delimiter     := Sep;
      Aux.DelimitedText := SList[i];
      Found := Aux.IndexOf(SearchedText) <> -1;
      if Found then
        Result := Aux[InxRetField];
    finally
      Aux.Free;
    end;
    Inc(i);
  end
end;

Lamentablemente algunas versiones antiguas de Delphi (como la que tengo) adolecen de un bug. Y este es, que sea cual fuere el separador especificado, incluye siempre el espacio (' ') como tal, y por tanto no funcionará.
Pero aplicando algunas modificaciones que reemplacen los espacios por un caracter que sea inexistente en los datos, se puede lograr "esquivar" el bug:
Código Delphi [-]
// En el ejemplo mi caracter inexistente será  '~' (126)
function GetTextField(const SearchedText: string; SList: TStrings;
  const InxRetField: Integer; const Sep: Char): string;
const
  NONEXISTCHAR = #126;
var
  Aux: TStrings;
  i  : Integer;
  Found: Boolean;
begin
  Result := '';
  i      := 0;
  Found  := False;
  while not Found and (i < SList.Count) do
  begin
    Aux := TStringList.Create;
    try
      Aux.Delimiter     := Sep;
      Aux.DelimitedText := StringReplace(SList[i], ' ', NONEXISTCHAR , [rfReplaceAll]);
      Found := Aux.IndexOf(StringReplace(SearchedText, ' ', NONEXISTCHAR, [rfReplaceAll])) <> -1;
      if Found then
        Result := StringReplace(Aux[InxRetField], NONEXISTCHAR, ' ', [rfReplaceAll]);
    finally
      Aux.Free;
    end;
    Inc(i);
  end
end;

Llamada de ejemplo (para ambos casos):
Código Delphi [-]
var
  List: TStrings;
begin
  List := TStringList.Create;
  try
    List.LoadFromFile('C:\LINEAS.TXT');
    Edit2.Text := GetTextField(Edit1.Text, List, 3, '|');
  finally
    List.Free;
  end;
end;
El argumento InxRetField tiene como cota inferior cero y como superior el número de campos -1 (para tu caso sería 11-1).

Saludos.


La franja horaria es GMT +2. Ahora son las 04:27:20.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi