¿Cómo obtengo los resultados de una consulta MySQL para mostrar en un cxGrid?
Estoy usando Delphi 5 y quiero mostrar los resultados de una consulta MySQL en un cxGrid. Tengo cxGrid, cxGridLevel y cxGridDBTableView configurados de la forma predeterminada cuando se agregan a un formulario. El DataController.DataSource para cxGridDBTableView es un TDataSource denominado DSNewKits con su conjunto de datos establecido en tMySQLQuery denominado NewKitsQry.
Cuando llega el momento de mostrar los datos, establezco la propiedad Enabled de DSNewKits en false, ejecuto el método Close de NewKitsQry, luego establezco la propiedad Enabled de DSNewKits en true, establezco la propiedad SQL.Text de NewKitsQry y ejecuto el método Open NewKitsQry . Luego tengo un cuadro de diálogo de mensaje que muestra la cantidad de resultados en la consulta, y hay 408, por lo que sé que la consulta funciona correctamente. La cuadrícula muestra filas y columnas con líneas en el medio, sin el mensaje "No hay datos para mostrar", pero todas las celdas están en blanco.
He intentado hacer estos pasos en un orden diferente, comentando algunos de ellos, etc., pero nada hace que se muestren los datos. Estoy seguro de que me estoy perdiendo algo simple y/o obvio, pero no pude encontrar un ejemplo en línea. ¡Gracias por cualquier ayuda que puedas dar!
(Editado para incluir código) Aquí está mi código:
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxControls, cxGridCustomView, cxGrid, ExtCtrls, Db,
mySQLDbTables, ovcbase, ovcfiler, ovcstore,
gECCConst,
StdCtrls;
type
Tf_cw_cxgrid_db = class(TForm)
WebCatDB: TmySQLDatabase;
NewKitsQry: TmySQLQuery;
DSNewKits: TDataSource;
Panel1: TPanel;
cxNewKitsGrid: TcxGrid;
cxNewKitsGridDBTableView1: TcxGridDBTableView;
cxNewKitsGridDBTableView1CompanyID: TcxGridDBColumn;
cxNewKitsGridDBTableView1RegionID: TcxGridDBColumn;
cxNewKitsGridDBTableView1BranchID: TcxGridDBColumn;
cxNewKitsGridDBTableView1CustID: TcxGridDBColumn;
cxNewKitsGridDBTableView1Username: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitID: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitComment: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitEffDate: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitExpDate: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitNote: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitType: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitFlags: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitTab: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitAddDate: TcxGridDBColumn;
cxNewKitsGridDBTableView1KitEditedDate: TcxGridDBColumn;
cxNewKitsGridDBTableView1Line: TcxGridDBColumn;
cxNewKitsGridDBTableView1ProductID: TcxGridDBColumn;
cxNewKitsGridDBTableView1MfgProdID: TcxGridDBColumn;
cxNewKitsGridDBTableView1PartNum: TcxGridDBColumn;
cxNewKitsGridDBTableView1ProductDesc: TcxGridDBColumn;
cxNewKitsGridDBTableView1Qty: TcxGridDBColumn;
cxNewKitsGridDBTableView1RefQty: TcxGridDBColumn;
cxNewKitsGridDBTableView1UnitPrice: TcxGridDBColumn;
cxNewKitsGridDBTableView1UnitPriceType: TcxGridDBColumn;
cxNewKitsGridDBTableView1UofM: TcxGridDBColumn;
cxNewKitsGridDBTableView1PSUofM: TcxGridDBColumn;
cxNewKitsGridDBTableView1UNSPSC: TcxGridDBColumn;
cxNewKitsGridDBTableView1ItemNote: TcxGridDBColumn;
cxNewKitsGridDBTableView1ItemGroupID: TcxGridDBColumn;
cxNewKitsGridDBTableView1ItemDrpDnHdr: TcxGridDBColumn;
cxNewKitsGridDBTableView1ItemSection: TcxGridDBColumn;
cxNewKitsGridDBTableView1ItemFlags: TcxGridDBColumn;
cxNewKitsGridDBTableView1ItemAddDate: TcxGridDBColumn;
cxNewKitsGridDBTableView1ItemEditedDate: TcxGridDBColumn;
cxNewKitsGrid1Level1: TcxGridLevel;
RegistryStore: TOvcRegistryStore;
userqry: TmySQLQuery;
Button1: TButton;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
f_cw_cxgrid_db: Tf_cw_cxgrid_db;
implementation
{$R *.DFM}
procedure Tf_cw_cxgrid_db.FormShow(Sender: TObject);
var
Server : String;
User : String;
Passwd : String;
DBName : String;
Button : Integer;
WCPath : String;
begin
RegistryStore.Open;
Server := RegistryStore.ReadString( 'SBAdmin', 'Host', '127.0.0.1');
User := RegistryStore.ReadString( 'SBAdmin', 'User', '');
Passwd := RegistryStore.ReadString( 'SBAdmin', 'Password', '');
DBName := RegistryStore.ReadString( 'SBAdmin', 'Database', WebCatDefUserDBName ); { caw 7-24-20 }
RegistryStore.Close;
WebCatDB.Host := Server;
WebCatDB.UserName := User;
WebCatDB.UserPassword := Passwd;
WebCatDB.DatabaseName := 'WEBCAT_' + DBName;
end;
procedure Tf_cw_cxgrid_db.Button1Click(Sender: TObject);
begin
DSNewKits.Enabled := False;
NewKitsQry.Close;
try
DSNewKits.Enabled := True;
NewKitsQry.SQL.Text := 'SELECT KitHdrs.CompanyID, KitHdrs.RegionID, KitHdrs.BranchID, KitHdrs.CustID, ' +
'KitHdrs.Username, KitHdrs.KitID, KitHdrs.KitComment, KitHdrs.KitEffDate, ' +
'KitHdrs.KitExpDate, KitHdrs.KitNote, KitHdrs.KitType, KitHdrs.KitFlags, KitHdrs.KitTab, ' +
'KitHdrs.KitAddDate, KitHdrs.KitEditedDate, KitLines.Line, KitLines.ProductID, ' +
'KitLines.MfgProdID, KitLines.PartNum, KitLines.ProductDesc, KitLines.Qty, ' +
'KitLines.RefQty, KitLines.UnitPrice, KitLines.UnitPriceType, KitLines.UofM, ' +
'KitLines.PSUofM, KitLines.UNSPSC, KitLines.ItemNote, KitLines.ItemGroupID, ' +
'KitLines.ItemDrpDnHdr, KitLines.ItemSection, KitLines.ItemFlags, ' +
'KitLines.ItemAddDate, KitLines.ItemEditedDate ' +
'FROM KitHdrs JOIN KitLines ON KitHdrs.KitSeq = KitLines.KitSeq;';
NewKitsQry.Open;
cxNewKitsGridDBTableView1.DataController.CreateAllItems;
MessageDlg( 'There are ' + IntToStr( NewKitsQry.RecordCount ) + ' records.', mtInformation, [mbOK], 0 );
except
MessageDlg( 'There was an error displaying the kit databases.', mtError, [mbOK], 0 );
end;
end;
end.
Respuestas
Aunque cxGrid es un buen componente, el hecho de que tenga tantas propiedades profundamente anidadas puede hacer que sea bastante desalentador configurar un cxGrid desde cero.
Creé el siguiente ejemplo para mostrar cómo crear y configurar un cxGrid completamente en código para que pueda ver fácilmente lo mínimo que debe hacerse. Utiliza un TClientDataSet, que se completa en el código, para proporcionar los datos de la cuadrícula para que el ejemplo sea completamente independiente. Sería trivial adaptarlo a un conjunto de datos MySql existente.
type
TForm1 = class(TForm)
CDS1: TClientDataSet;
DS1: TDataSource;
DBNavigator1: TDBNavigator;
Button1: TButton;
procedure FormCreate(Sender: TObject);
private
protected
public
cxGrid : TcxGrid;
cxLevel : TcxGridLevel;
cxView : TcxGridDBTableView;
end;
[...]
// This is a utility function to create TFields in code
function CreateField(AFieldClass : TFieldClass; AOwner : TComponent; ADataSet : TDataSet;
AFieldName, AName : String; ASize : Integer; AFieldKind : TFieldKind) : TField;
begin
Result := AFieldClass.Create(AOwner);
Result.FieldKind := AFieldKind;
Result.FieldName := AFieldName;
Result.Name := AName;
Result.Size := ASize;
Result.DataSet := ADataSet;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i : Integer;
Field : TField;
begin
// All the code to set up the cxGrid is in this event handler
// First, create the Fields of the ClientDataSet
Field := CreateField(TIntegerField, Self, CDS1, 'ID', 'CDS1ID', 0, fkData);
Field := CreateField(TIntegerField, Self, CDS1, 'Qty', 'CDS1Qty', 0, fkData);
Field := CreateField(TCurrencyField, Self, CDS1, 'UnitPrice', 'CDS1UnitPrice', 0, fkData);
CDS1.CreateDataSet;
CDS1.IndexFieldNames := 'ID';
// Next, populate the CDS with a few records
CDS1.InsertRecord([1, 1, 1]);
CDS1.InsertRecord([2, 2, 5]);
CDS1.InsertRecord([3, 3, 6]);
CDS1.First;
DS1.DataSet := CDS1;
// Now, create a cxGrid to display the CDS data
cxGrid := TcxGrid.Create(Self);
cxGrid.Parent := Self;
cxGrid.Width := 400;
cxLevel := cxGrid.Levels.Add;
cxLevel.Name := 'Firstlevel';
cxView := cxGrid.CreateView(TcxGridDBTableView) as TcxGridDBTableView;
cxView.Name := 'ATableView';
cxView.DataController.KeyFieldNames := 'ID';
cxLevel.GridView := cxView;
cxView.DataController.DataSource := DS1;
cxView.DataController.CreateAllItems;
end;