PDA

Ver la Versión Completa : Agregar ID a checkboxlist en delphi


teecweb
03-03-2013, 15:21:59
:D Holas
Este es el codigo para agregar CheckListBox dinamico pero a este codigo quiero agregar el Id por checkbox y asi depues hacer el recorrido de la lista de checkbox ..por favor me podrian indicar como ahcer la sintaxis para agregar el ID de cada checkbox....eh buscado en google y no eh encontrado gracias por su respuesta.


scale :=8;
for i := 0 to listado.Count - 1 do
begin
j :=5;
scale :=scale+ (j+15);
CheckListBox := TNewCheckListBox.Create(Page);
CheckListBox.Top := Buttona.Top + Buttona.Height + ScaleY(scale);
CheckListBox.Width := 410;
CheckListBox.Height :=40;
CheckListBox.Flat := True;
CheckListBox.Parent := Page.Surface;
CheckListBox.OnClick:=@uninstaller;
CheckListBox.AddCheckBox(listado[i], 'qwqw', 0, False, True, True, True, nil);
end;

ecfisa
03-03-2013, 18:36:36
Hola teecweb.

No entiendo a que te refieres con "ID".

Si es a la posición que ocupa el ítem actual, la podes obtener mediante la propiedad ItemIndex:

Caption:= IntToStr(Integer(CheckListBox1.ItemIndex));


En cambio si "ID" se refiere al campo de un DataSet, un ejemplo para cargar un campo de texto y el campo "ID" :

procedure TForm1.btnCargarClick(Sender: TObject);
begin
with DataSet do
begin
Open;
while not Eof do
begin
CheckListBox1.AddItem(FieldByName('CAMPO1').AsString,
TObject(FieldByName('ID').AsInteger));
Next
end;
Close
end
end;


Para obtener el valor: (en el ejemplo se muestra)

procedure TForm1.CheckListBox1Click(Sender: TObject);
begin
with CheckListBox1 do
ShowMessage('Item: '+Items[ItemIndex] + #10#13 +
'ID: ' + IntToStr(Integer(Items.Objects[ItemIndex])));
end;


Saludos.

teecweb
04-03-2013, 00:48:10
Holas..gracias por surespuesta

con respecto a tu primer codigo..devuelve el indice de los checbox en un checkboxlist:
Caption:= IntToStr(Integer(CheckListBox1.ItemIndex));

lo eh agregrado asi en la funcion de onclick por checbox:

procedure uninstaller(Sender: TObject);
var path String;
begin
if (Sender is TNewCheckListBox) then
begin
path:= IntToStr(Integer(CheckListBox.ItemIndex));
MsgBox(path,mbInformation, MB_OK);
end;


por ejemplo mi for para la creacion de checkbolist que se encuentra arriba ..devuelve asi
[checkbox] = es la casilla de checkbox

[checkbox]'aaaaa'
[checkbox]'aaaaa'
[checkbox]'aaaaa'
[checkbox]'aaaaa'
[checkbox]'aaaaa'

Entonces cada vez que hago click a mi funcion uninstaller me deberia devolver la posicion de los checkboxlist por MsgBox :
0
1
2
3
4
pero en cambio me devuelve asi segun el codigo que usted me envio:
Caption:= IntToStr(Integer(CheckListBox1.ItemIndex));

-1
-1
-1
-1
0

En realidad llevo una
2semana en el lenguaje delphi ..por favor alguna solucion
Tambien quisiera saber cual es el codigo para retornar el text de los checkbox al hacer click en cada uno de ellos..gracias por su respuesta..estare al tanto

ecfisa
04-03-2013, 01:19:47
Hola teecweb.

No cuál sea el contenido del TCheckListBox, pero basta con que realices esta simple prueba en una nueva aplicación para comprobar que la propiedad ItemIndex devuelve el valor del índice actual:

...
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
for i:= 1 to 10 do
CheckListBox1.Items.Add('Item '+IntToStr(i));
end;

procedure TForm1.CheckListBox1Click(Sender: TObject);
begin
ShowMessage('Indice item actual: '+IntToStr(Integer(CheckListBox1.ItemIndex))+#10+
'Valor item actual : '+CheckListBox1.Items[CheckListBox1.ItemIndex]);
end;
...

Es decir que si el CheckListBox tiene algún contenido, el código:

procedure TForm1.CheckListBox1Click(Sender: TObject);
begin
Caption:= IntToStr(Integer(CheckListBox1.ItemIndex));
end;

mostrará el índice actualmente seleccionado.

Lo que podría suceder es que no estés llamándo el código en el evento OnClick del TCheckListBox, en ese caso sí es necesario comprobar el valor de la propiedad ItemIndex:

procedure TForm1.Button1Click(Sender: TObject);
begin
if CheckListBox1.ItemIndex = -1 then
ShowMessage('¿ No le parece que debería seleccionar algo primero ?')
else
Caption:= IntToStr(Integer(CheckListBox1.ItemIndex));
end;


Saludos.

teecweb
04-03-2013, 01:41:08
ok, muchas gracias estare probando el codigo

teecweb
04-03-2013, 02:51:29
Asi creo mi control de checkbolist..el codigo es para un instalador inno setup y innosetup utiliza el pascal que es parecido al delphi bueno es lo que segun investigue

[Code]
//CODIGO PARA ONCLICK

var
Page: TWizardPage;
Buttona TNewButton;
CheckListBox1: TNewCheckListBox;

procedure uninstaller(Sender: TObject);
begin
MsgBox('Indice item actual: '+IntToStr(Integer(CheckListBox1.ItemIndex)),mbInformation, MB_OK);

end;

procedure CreateTheWizardPages;
var

Edit: TNewEdit;
PasswordEdit: TPasswordEdit;
listado: TStrings;
inicio: Integer;
scale : Integer;
scale1:Integer;
j:Integer;
n: integer;

begin
{ TButton and others }
Page := CreateCustomPage(wpSelectDir, 'Custom wizard page controls', 'TButton and others');

Buttona := TNewButton.Create(Page);
Buttona.Width := ScaleX(75);
Buttona.Height := ScaleY(23);
Buttona.Caption := 'TNewButton';
Buttona.Parent := Page.Surface;
Buttona.Visible := true;
Buttona.OnClick := @ButtonOnClick;

scale :=8;
for inicio:= 1 to 10 do
begin
CheckListBox1 := TNewCheckListBox.Create(Page);
j :=5;
scale :=scale+ (j+15);
CheckListBox1 := TNewCheckListBox.Create(Page);//TNewCheckListBox.Create(WizardForm.ScriptDlgPanel);
CheckListBox1.Top := Buttona.Top + Buttona.Height + ScaleY(scale);
CheckListBox1.Width := 410;
CheckListBox1.Height :=40;
CheckListBox1.Parent := Page.Surface;
CheckListBox1.OnClick:=@uninstaller;
CheckListBox1.AddCheckBox('Item'+IntToStr(inicio), 'qwqw', 0, False, True, True, True, nil);
end;
end;


ya eh probado el codigo que usted me mando..y lo eh hecho asi como esta arriba..aun asi me bota el index -1..gracias por su pronta respuesta...En el codigo que me envio hay eventos asi 'TForm1.FormCreate' en inno setup no se genera estos eventos .

nlsgarcia
04-03-2013, 05:10:27
teecweb,


...cada vez que hago click a mi funcion uninstaller me deberia devolver la posicion de los checkboxlist por MsgBox...



Revisa este código:

procedure TForm1.BitBtn1Click(Sender: TObject);
var
i : Integer;
Index : Integer;
begin
ListBox1.Clear;
for i := 0 to CheckListBox1.Count - 1 do
begin
Index := CheckListBox1.Items.IndexOf(CheckListBox1.Items.Strings[i]);
ListBox1.Items.Add(IntToStr(Index));
end;
end;

El código anterior devuelve el índice de cada elemento de un control TCheckListBox en un control TListBox.


Revisa este código:

procedure TForm1.CheckListBoxClick(Sender: TObject);
var
i : Integer;
begin
for i := 0 to CheckListBox1.Count - 1 do
if CheckListBox1.Selected[i] then
ShowMessage(IntToStr(i));
end;

El código anterior devuelve el índice de un elemento seleccionado del control TCheckListBox por medio del evento OnClick.


Revisa este código:

procedure TForm1.CheckListBoxClick(Sender: TObject);
begin
ShowMessage(IntToStr(CheckListBox1.ItemIndex));
end;

Este código es una variante más simple del anterior por medio del evento OnClick.


Los códigos anteriores funcionan en Delphi, quizás funcionen de forma similar en Inno Setup y se puedan adaptar a tu Instalador.

Espero sea útil :)

Nelson.

ecfisa
04-03-2013, 07:13:48
Hola teecweb.

Mi respuesta fué por el título de tu primer mensaje "Agregar ID a checkboxlist en delphi", pero tratándose de Inno setup cambia un poco la cosa.

Nunca había realizado un script para Inno setup, pero basándome en parte en tu código y revisando un poco aquí: Pascal Scripting: Support Classes Reference (http://www.jrsoftware.org/ishelp/index.php?topic=scriptclasses), hice unas pruebas y en este ejemplo se muestran el texto y los índices de los items seleccionados en el TNewChekListBox como respuesta del evento OnClick de Buttona:

[Setup]
AppName='Test'
AppVerName='Test'
DefaultDirName={pf}\test

[code]
var
Page: TWizardPage;
Buttona: TNewButton;
CheckListBox1: TNewCheckListBox;

procedure ButtonOnClick(Sender: TObject);
var
i: Integer;
begin
for i:= 0 to CheckListBox1.Items.Count -1 do
if CheckListBox1.Checked[i] then // ¿ El item está seleccionado ?
MsgBox('Caption: ' + CheckListBox1.Items[i]+ #10#13 + // Caption del item
'Indice : ' + IntToStr(i), mbInformation, MB_OK); // Indice del item
end;

procedure CreateTheWizardPages;
var
inicio: Integer;
scale : Integer;
begin
Page := CreateCustomPage(wpSelectDir, 'Custom wizard page controls', 'TButton and others');

Buttona := TNewButton.Create(Page);
Buttona.Width := ScaleX(75);
Buttona.Height := ScaleY(23);
Buttona.Caption := 'TNewButton';
Buttona.Parent := Page.Surface;
Buttona.Visible := true;
Buttona.OnClick := @ButtonOnClick;

CheckListBox1 := TNewCheckListBox.Create(Page);
CheckListBox1.Width := 410;
CheckListBox1.Height := 180;
CheckListBox1.Parent := Page.Surface;
CheckListBox1.ItemIndex:= 0;
CheckListBox1.Top := Buttona.Top + Buttona.Height + ScaleY(scale);

for inicio:= 1 to 5 do
CheckListBox1.AddCheckBox('Item' + IntToStr(inicio), IntToStr(inicio), 0, False, True, True, True, nil);
end;

procedure InitializeWizard();
begin
CreateTheWizardPages
end;

Espero te oriente para lograr lo que estás buscando.

Saludos.:)

teecweb
04-03-2013, 11:35:47
Gracias por sus respuestas estare probando el codigo

teecweb
04-03-2013, 14:18:21
Holas si ya funciono.gracias...pero quisiera hacer una consulta mas:

Una vez que ya recorrio bien los indices y recuperar los nombres de los check se procede a desistalar :
por ejemplo la lista que se recorre:
c:\Program Files\rcv1.1\
c:\Program Files\rcv1.2\




procedure ButtonOnClick(Sender: TObject);
var
i: Integer;
var path,FileName: String;
begin
path := CheckListBox1.Items[i];
if MsgBox('Do you really want to delete ' + ExtractFileDir(path) + '?', mbConfirmation, MB_YESNO) = idYes then
begin
for i:= 0 to CheckListBox1.Items.Count -1 do
//unistaler
begin
if DirExists(ExtractFileDir(path)) then
begin
CheckListBox1.Checked[i]:=true;
//Aqui me llega un path por ejemplo : c:\Program Files\rcv1.2\ ..y dentro hay un directorio llamado
//Desinstalar dentro de este directorio hay un 'unins000.exe' y shellexec lo ejecuta mediante el procedimeinto 'desistalarItem'
FileName:=ExtractFileDir(path)+'\Desinstalar\'+'unins000.exe';
desistalarItem(FileName);
end
else
MsgBox('no existe',mbInformation, MB_OK);
end;
end;
end;

//procedimiento para desistalacion los .exe existentes
***********Mi dificultad es cuando shellexec se ejecuta ya sea para una desistalacion correcta o incorrecta sale del bucle y vuelve a recorrer el bucle..y yo en realidad no necesito que salga del bucle sino que siga con el siguiente indice..



si algo fallo en la desistalacion sale el error y sino ejecuta normalmente y el bucle empieza denuevo
y cuando el bucle empieza denuevo ahi es mi dificultad porque necesito que normalmente siga el bucle y no salga de el

procedure desistalarItem(const FileName: string);
var
ErrorCode: Integer;
begin
if not ShellExec('',FileName,'', '', SW_SHOW, ewNoWait, ErrorCode) then
begin
// handle failure if necessary
MsgBox('DeinitializeSetup:' #13#13 'Execution of ''' + FileName + ''' failed. ' + SysErrorMessage(ErrorCode) + '.', mbError, MB_OK);
end
end;


por favor si hay alguna suegerencia estare muy pendiente..gracias por sus respuestas

nlsgarcia
05-03-2013, 04:43:58
teecweb,


...y cuando el bucle empieza denuevo ahi es mi dificultad porque necesito que normalmente siga el bucle y no salga de el...


El código que publicastes en el Msg #10 lo modifique según entiendo como debería funcionar tu Desinstalador en Inno Setup.

Revisa este código:

procedure ButtonOnClick(Sender: TObject);
var
i : Integer;
path,FileName : String;

begin
if MsgBox('Do you really want to delete ' + ExtractFileDir(path) + '?', mbConfirmation, MB_YESNO) = idYes then
begin
for i := 0 to CheckListBox1.Items.Count - 1 do
begin
path := CheckListBox1.Items[i];
if CheckListBox1.Checked[i] = true then
if DirExists(ExtractFileDir(path)) then
begin
FileName := ExtractFileDir(path) + '\Desinstalar' + '\unins000.exe';
DesistalarItem(FileName);
end
else
MsgBox('No Existe un Desinstalador Asociado',mbInformation, MB_OK);
end;
end;
end;

procedure DesistalarItem(const FileName: string);
var
ErrorCode : Integer;

begin
if not Exec(FileName,'', '', SW_SHOW, ewWaitUntilTerminated, ErrorCode) then
begin
MsgBox('DeinitializeSetup:' #13#13 'Execution of ''' + FileName + ''' failed. ' + SysErrorMessage(ErrorCode) + '.', mbError, MB_OK);
end
end;

El código anterior recorre el arreglo de Items del control TCheckListbox y por cada item seleccionado llama al procedimiento DesistalarItem

El cambio de ShellExec por Exec esta basado en la información de este link: http://www.jrsoftware.org/ishelp/index.php?topic=scriptclasses

Nota: Este código no esta probado en Inno Setup.

Espero sea útil :)

Nelson.

teecweb
05-03-2013, 16:41:31
gracias por su respuesta probare el codigo.. :D

teecweb
08-03-2013, 16:05:47
Funciono perfectamente !!..gracias