Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > OOP
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 16-04-2009
Avatar de mRoman
mRoman mRoman is offline
Miembro
 
Registrado: nov 2003
Posts: 599
Poder: 21
mRoman Va por buen camino
Mover o cambiar lineas dentro de un ListBox

Hola amigos.

Voy al grano (de lleno al problema), como se dice en México, tengo un ListBox el cual lleno con algunos datos de 2 campos, y actualmente lo programe de una forma que actualmente ya no es práctico. Ahora necesito mover o cambiar de linea algun item que el usuario haya seleccionado, a otra linea ya sea antes o despues de la actual, esto para que?, digamos q este orden sera con el que se grabe en BD.

Bueno, talvez tengan una mejor idea de como mejorar esto. Estoy tratando de utilizar la tecla Shift+(Tecla de Flecha hacia arriba o hacia abajo), pero no me sale.

Seré mas explicito en lo que quiero hacer, quiero que el mismo usuario usando las teclas de Shift+flecha, pueda cambiar de posicion del registro que el haya seleccionado, al mismo tiempo que tambien pueda insertar y borrar, sé que talvez esto pueda resolverlo con el DataSet y asociarle un Navigator, pero no es factible por otras razones, largars de explicar, bueno el caso es que al final ya que el usuario haya terminado con el acomodo, tendra que grabar lo realizado y el mismo sistema les asignara un numero....el cual será consecutivo en el orden en que el usuario los haya ordernado.

ANTES DE ORDERNAR
CAMPO1 CAMPO1
23234 A
23090 H
23330 J

DESPUES DE ORDENAR
23330 J
23234 A
23090 H

He encontrado algunos ejemplos los cuales estoy estudiando, por ejemplo pasar lineas de ListBox a otro ListBox....esto me podria servir q en vez de utilizar otro ListBox use el mismo ListBox....bueno estoy en ese proceso, pero de igual manera les agradezco sus comentarios.

codigo q estoy estudiando
Código Delphi [-]
unit DragOnDualListBox;

interface

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

type
  TDualListDlg = class(TForm)
    OKBtn: TButton;
    SrcList: TListBox;
    DstList: TListBox;
    SrcLabel: TLabel;
    DstLabel: TLabel;
    IncludeBtn: TSpeedButton;
    IncAllBtn: TSpeedButton;
    ExcludeBtn: TSpeedButton;
    ExAllBtn: TSpeedButton;
    Label1: TLabel;
    Label2: TLabel;
    procedure IncludeBtnClick(Sender: TObject);
    procedure ExcludeBtnClick(Sender: TObject);
    procedure IncAllBtnClick(Sender: TObject);
    procedure ExcAllBtnClick(Sender: TObject);
    procedure DstListDragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure DstListDragDrop(Sender, Source: TObject; X, Y: Integer);
    procedure SrcListDragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure SrcListDragDrop(Sender, Source: TObject; X, Y: Integer);
    procedure OKBtnClick(Sender: TObject);
    procedure Label2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure MoveSelected(List: TCustomListBox; Items: TStrings);
    procedure SetItem(List: TListBox; Index: Integer);
    function GetFirstSelection(List: TCustomListBox): Integer;
    procedure SetButtons;
  end;

var
  DualListDlg: TDualListDlg;

implementation

{$R *.dfm}

uses
  ShellAPI;

procedure TDualListDlg.IncludeBtnClick(Sender: TObject);
var
  Index: Integer;
begin
  Index := GetFirstSelection(SrcList);
  MoveSelected(SrcList, DstList.Items);
  SetItem(SrcList, Index);
end;

procedure TDualListDlg.ExcludeBtnClick(Sender: TObject);
var
  Index: Integer;
begin
  Index := GetFirstSelection(DstList);
  MoveSelected(DstList, SrcList.Items);
  SetItem(DstList, Index);
end;

procedure TDualListDlg.IncAllBtnClick(Sender: TObject);
var
  I: Integer;
begin
  for I := 0 to SrcList.Items.Count - 1 do
    DstList.Items.AddObject(SrcList.Items[i], 
      SrcList.Items.Objects[i]);
  SrcList.Items.Clear;
  SetItem(SrcList, 0);
end;

procedure TDualListDlg.ExcAllBtnClick(Sender: TObject);
var
  I: Integer;
begin
  for I := 0 to DstList.Items.Count - 1 do
    SrcList.Items.AddObject(DstList.Items[i], DstList.Items.Objects[i]);
  DstList.Items.Clear;
  SetItem(DstList, 0);
end;

procedure TDualListDlg.MoveSelected(List: TCustomListBox; Items: TStrings);
var
  I: Integer;
begin
  for I := List.Items.Count - 1 downto 0 do
    if List.Selected[i] then
    begin
      Items.AddObject(List.Items[i], List.Items.Objects[i]);
      List.Items.Delete(I);
    end;
end;

procedure TDualListDlg.SetButtons;
var
  SrcEmpty, DstEmpty: Boolean;
begin
  SrcEmpty := SrcList.Items.Count = 0;
  DstEmpty := DstList.Items.Count = 0;
  IncludeBtn.Enabled := not SrcEmpty;
  IncAllBtn.Enabled := not SrcEmpty;
  ExcludeBtn.Enabled := not DstEmpty;
  ExAllBtn.Enabled := not DstEmpty;
end;

function TDualListDlg.GetFirstSelection(List: TCustomListBox): Integer;
begin
  for Result := 0 to List.Items.Count - 1 do
    if List.Selected[Result] then Exit;
  Result := LB_ERR;
end;

procedure TDualListDlg.SetItem(List: TListBox; Index: Integer);
var
  MaxIndex: Integer;
begin
  with List do
  begin
    SetFocus;
    MaxIndex := List.Items.Count - 1;
    if Index = LB_ERR then Index := 0
    else if Index > MaxIndex then Index := MaxIndex;
    Selected[Index] := True;
  end;
  SetButtons;
end;

procedure TDualListDlg.DstListDragOver(Sender, Source: TObject; X,
  Y: Integer; State: TDragState; var Accept: Boolean);
begin

  // Se debe aceptar
  Accept := (Source = SrcList);

end;

procedure TDualListDlg.DstListDragDrop(Sender, Source: TObject; X,
  Y: Integer);
begin
  // Llamar al oton que pasa de Izq a derecha
  Self.IncludeBtnClick(nil);
end;

procedure TDualListDlg.SrcListDragOver(Sender, Source: TObject; X,
  Y: Integer; State: TDragState; var Accept: Boolean);
begin
  // Se debe aceptar
  Accept := (Source = DstList);
end;

procedure TDualListDlg.SrcListDragDrop(Sender, Source: TObject; X,
  Y: Integer);
begin
  // Llamar al boton que pasa de der. a Izq
  Self.ExcludeBtnClick(nil);
end;

procedure TDualListDlg.OKBtnClick(Sender: TObject);
begin
  // cerrar
  Self.Close;
end;

procedure TDualListDlg.Label2Click(Sender: TObject);
begin
    ShellExecute(Handle,
             'open',
             'http://neftali.clubdelphi.com/',
             nil,
             nil,
             SW_SHOW);
end;

end.
__________________
Miguel Román

Afectuoso saludo desde tierras mexicanas....un aguachile?, con unas "cetaseas" bien "muertas"?, VENTE PUES !!
Responder Con Cita
  #2  
Antiguo 16-04-2009
Avatar de mRoman
mRoman mRoman is offline
Miembro
 
Registrado: nov 2003
Posts: 599
Poder: 21
mRoman Va por buen camino
Despues de poster mi anterior mensaje me encontre este otro que lo voy a analizar...pero de todas maneras se reciben opiniones.
http://www.clubdelphi.com/foros/showthread.php?t=37143
__________________
Miguel Román

Afectuoso saludo desde tierras mexicanas....un aguachile?, con unas "cetaseas" bien "muertas"?, VENTE PUES !!
Responder Con Cita
  #3  
Antiguo 16-04-2009
Avatar de Caro
*Caro* Caro is offline
Moderadora
 
Registrado: jul 2004
Ubicación: Cochabamba, Bolivia
Posts: 2.544
Poder: 22
Caro Va por buen camino
Hola mRoman, yo utilizaría el procedimiento ExChange del ListBox:

Código Delphi [-]
//Para mover el Item hacia arriba
var
 Indice : Integer;
begin
  if ListBox1.ItemIndex > 0 then
   begin
    Indice := ListBox1.ItemIndex;
    ListBox1.Items.Exchange(Indice, Indice-1);
   end
  else
   ListBox1.ItemIndex := 0;

 
//Para mover el item hacia abajo
  if ListBox1.ItemIndex < ListBox1.Items.Count-1 then
   begin
    Indice := ListBox1.ItemIndex;
    ListBox1.Items.Exchange(Indice, Indice+1);
   end
  else
   ListBox1.ItemIndex := ListBox1.Items.Count-1;

Saluditos
__________________
Disfruten cada minuto de su vida a lado de sus seres queridos como si fuese el ultimo, uno nunca sabe lo que puede pasar.
Responder Con Cita
  #4  
Antiguo 16-04-2009
Avatar de mRoman
mRoman mRoman is offline
Miembro
 
Registrado: nov 2003
Posts: 599
Poder: 21
mRoman Va por buen camino
Orale !!!...muchas gracias, me parece algo digerible....gracias por aportar Caro. Deja lo pruebo
__________________
Miguel Román

Afectuoso saludo desde tierras mexicanas....un aguachile?, con unas "cetaseas" bien "muertas"?, VENTE PUES !!
Responder Con Cita
  #5  
Antiguo 16-04-2009
Avatar de mRoman
mRoman mRoman is offline
Miembro
 
Registrado: nov 2003
Posts: 599
Poder: 21
mRoman Va por buen camino
ok...gracias funciona !, he aprendido algo mas, ya lo probe pero ahora hace resolver algo, en lo cual estoy trabajando, el cual combinar las teclas Shift+felcha, para que el usuario pueda "navegar" por las lineas del lisbox libremente y cuando el quiera mover lo haga oprimiendo shift+flecha....

Si tienes alguna idea...bienvenida. y nuevamente gracias !
__________________
Miguel Román

Afectuoso saludo desde tierras mexicanas....un aguachile?, con unas "cetaseas" bien "muertas"?, VENTE PUES !!
Responder Con Cita
  #6  
Antiguo 16-04-2009
Avatar de mRoman
mRoman mRoman is offline
Miembro
 
Registrado: nov 2003
Posts: 599
Poder: 21
mRoman Va por buen camino
Cita:
Empezado por mRoman Ver Mensaje
ok...gracias funciona !, he aprendido algo mas, ya lo probe pero ahora hace resolver algo, en lo cual estoy trabajando, el cual combinar las teclas Shift+felcha, para que el usuario pueda "navegar" por las lineas del lisbox libremente y cuando el quiera mover lo haga oprimiendo shift+flecha....

Si tienes alguna idea...bienvenida. y nuevamente gracias !
LISTO YA ESTA .... esta es la solucion.
Código Delphi [-]
procedure TfrmRuta.btnArribaClick(Sender: TObject);
var
  Indice:integer;
begin
  inherited;
  if lBoxLecherias.ItemIndex>0 then
  begin
      indice:=lBoxLecherias.ItemIndex;
      lBoxLecherias.Items.Exchange(Indice,indice-1);
  end
  else
      lBoxLecherias.ItemIndex:=0;

end;

procedure TfrmRuta.btnAbajoClick(Sender: TObject);
var
   Indice:Integer;
begin
  inherited;
   if lBoxLecherias.ItemIndex< lBoxLecherias.Items.Count-1 then
  begin
      indice:=lBoxLecherias.ItemIndex;
      lBoxLecherias.Items.Exchange(Indice,indice+1);
  end
  else
      lBoxLecherias.ItemIndex:=lBoxLecherias.Items.Count-1;

end;
procedure TfrmRuta.lBoxLecheriasKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  inherited;
   { Codigo que combina las teclas SHIFT y TECLAS DE FLECHA, para mover lineas hacia
    arriba o hacia abajo dentro del ListBox}
  if (ssShift in Shift) and (Key=VK_UP) then
       btnArribaClick(Sender);
  if (ssShift in Shift) and (Key=VK_DOWN) then
       btnAbajoClick(Sender);
end;

En este ejemplo, sucede algo raro, utilizando los botones el registro movido no pierde el focus, sigue posicionado en el registro movido,lo cual esta bien para el usuario para que no se pierda en el registro que movio, pero usando las combinaciones de teclas, lo sombreado se pasa al siguiente registro ya sea posterior o anterior con respecto a la nueva posicion....espero haberme explicado, revisare el codigo, se aceptan sugerencias.

MUCHISISISIMAS GRACIAS POR SU AYUDA.
__________________
Miguel Román

Afectuoso saludo desde tierras mexicanas....un aguachile?, con unas "cetaseas" bien "muertas"?, VENTE PUES !!
Responder Con Cita
  #7  
Antiguo 16-04-2009
Avatar de mRoman
mRoman mRoman is offline
Miembro
 
Registrado: nov 2003
Posts: 599
Poder: 21
mRoman Va por buen camino
Cita:
Empezado por mRoman Ver Mensaje
LISTO YA ESTA .... esta es la solucion.
[delphi]
procedure TfrmRuta.btnArribaClick(Sender: TObject);
var
Indice:integer;
begin
inherited;
if lBoxLecherias.ItemIndex>0 then
begin
indice:=lBoxLecherias.ItemIndex;
lBoxLecherias.Items.Exchange(Indice,indice-1);
end
else.....
Ya mejore el codigo del post anterior....
declare una variable privada para usarla en cualquier parte del codigo, llamada FlagUpDw de tipo integer.
Código Delphi [-]
  private
    { Private declarations }
    j,i:integer;
    FlagUpDw : integer;  public
    { Public declarations }
  end;

Y luego modifique un poco el codigo como sigue

Código Delphi [-]
procedure TfrmRuta.btnArribaClick(Sender: TObject);
var
  Indice:integer;
begin
  inherited;
  if lBoxLecherias.ItemIndex>0 then
  begin
      indice:=lBoxLecherias.ItemIndex;
      lBoxLecherias.Items.Exchange(Indice,indice-1);
      if FlagUpDw=1 then         
          lBoxLecherias.Selected[indice]:=true;  end
  else
      lBoxLecherias.ItemIndex:=0;

end;

procedure TfrmRuta.btnAbajoClick(Sender: TObject);
var
   Indice:Integer;
begin
  inherited;
   if lBoxLecherias.ItemIndex< lBoxLecherias.Items.Count-1 then
  begin
      indice:=lBoxLecherias.ItemIndex;
      lBoxLecherias.Items.Exchange(Indice,indice+1);
      if FlagUpDw=1 then
        lBoxLecherias.Selected[indice]:=true;
  end
  else
      lBoxLecherias.ItemIndex:=lBoxLecherias.Items.Count-1;

end;
procedure TfrmRuta.lBoxLecheriasKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  inherited;
   { Codigo que combina las teclas SHIFT y TECLAS DE FLECHA, para mover lineas hacia
    arriba o hacia abajo dentro del ListBox}
  if (ssShift in Shift) and (Key=VK_UP) then
  begin
       btnArribaClick(Sender);
  end;
  if (ssShift in Shift) and (Key=VK_DOWN) then
  begin
       btnAbajoClick(Sender);
  end;
  FlagUpDw:=1;
end;

procedure TfrmRuta.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  inherited;
  case Key of
  VK_F2 : Begin
               if not(dsRutaDistribucion.IsEmpty) then
               begin
                   if FindComponent('frmBuscarLech') = nil then
                         frmBuscarLech:=TfrmBuscarLech.Create(self);
                   frmBuscarLech.Show;
               end;
          end;
  end;
end;

procedure TfrmRuta.GroupBox1Enter(Sender: TObject);
begin
  inherited;
  FlagUpDw:=0;
end;

Y de esta manera puede solucionar que la parte sobreada siguiera sombreada para quede como referencia para el usuario y el vea que registro esta moviendo....tanto con los botones como con las combinaciones de teclas shift+flecha.

Se los dejo para futuras consultas de otros delphineros....

Creo q este hilo ha cumplido el objetivo, que era mover lineas dentro un ListBox hacia arriba y hacia abajo usando tanto conbinaciones de teclas (shift+flechas) como con botones.

Gracias por sus comentarios, aportaciones y orientaciones. GRACIAS.
__________________
Miguel Román

Afectuoso saludo desde tierras mexicanas....un aguachile?, con unas "cetaseas" bien "muertas"?, VENTE PUES !!

Última edición por mRoman fecha: 16-04-2009 a las 03:30:30.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Buscar dentro del ListBox FrianxD C++ Builder 9 06-03-2008 07:20:27
Mover todos los elementos entre dos listbox creus Varios 2 05-11-2006 11:59:37
Mover elementos de un listbox a otro creus Varios 2 05-11-2006 09:03:32
Mover posiciones dentro de un list Box creus Varios 13 04-11-2006 18:03:44
ListBox con líneas de colores. DarkByte Varios 2 01-08-2004 19:58:52


La franja horaria es GMT +2. Ahora son las 20:15:05.


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
Copyright 1996-2007 Club Delphi