如何根据checkListBox中多选的个数确定全局变量,以传递参数(60分)

C

cnnoah

Unregistered / Unconfirmed
GUEST, unregistred user!
我想在程序中实现如下功能:
form1.checkListBox选择了一项或多项后,把值作为form2的ADODataSet的数据集过滤条件,
比如下面:
select * from table1 where Col2='A' or Col2='B' or Col2='C'
ABC即为多选的值
现在的问题是在form间传递参数我用全局变量,如何设置全局变量?因为没有办法确定全
局变量的个数
 
用tstrings传递

 
我的作法是:
在TForm2中写一个方法,接收一个SQL字符串,然后创建窗体
而在TForm1中生成SQL,再调用TForm2中的方法
 
to Admy
能举个例子吗?
 
to Admy
用TStrings传递,最终不是还要把它一个个分开吗?不然如何识别它们,并把它们作为
动态参数传递呢?
能举个例子吗?
 
各选项间加分隔符,用串:

select * from table1 where Col2 pos(Col2,'A/B/C')>0
//==表示 col2 在 'A/B/C' 中根据数据库找类似这样的函数
 
用循环判断判断是否被选中,来设置字符串的值
 
gz

to jsxjd
什么叫"根据数据库找类似这样的函数"?
 
比如说,这样的函数在 delphi 中用 pos 可以完成。

但你现在执行的是SQL,是在数据库端执行的,在SQL中要用SQL本身支持的函数,
不能用Delphi 的函数。
这样的函数在不同数据库中很可能不同。
 
这是我以前的一个片段

procedure TFilterForm.bitUseFilterClick(Sender: TObject);
var sSQL:string;
i:integer;
bChecked:boolean; //此变量来表示列表中有没有选中项
begin
//先看有没有选中的项
bChecked:=false; //³õʼ»¯
for i:=0 to TypelistBox.Items.Count-1 do
if TypelistBox.Checked then
begin
bChecked:=true;
break; //有一项选中就可以了
end; //end for and if
if not bChecked then
begin
messagedlg('ÇëÏÈÑ¡ÖÐÒ»¸öÀà±ð½øÐйýÂË£¡',
mtError,[mbok],0);
exit;
end;

//合成SQL语句
sSQL:='select * from dtMain '; //此时长度为21,有一个空格
for i:=0 to TypelistBox.Items.Count-1 do
if TypelistBox.Checked then
sSQL:=sSQL+' sort='+''''+TypelistBox.Items+''''+' or';

{下句是看要不要过滤(从有没有OR可以知道,如要,则插入WHERE}
if pos('or',sSQL)>0 then
insert(' where',sSQL,21);

//去掉前面多余的or
delete(sSQL ,length(sSQL)-1,2);
sSQL:=sSQL+' and User="'+sCurUser+'"';
sSQL:=sSQL+' order by fullname';

DM.taMain.Active:=false;
DM.taMain.CommandText:=sSQL;
DM.TaMain.Open;
   bitCancelFilter.enabled:=true;
Mainform.mmiCancelFilter.enabled:=true;
Mainform.bitCancelFilter.enabled:=true;
MainForm.SetFilterStatus(true);
end;

以上 的操作如果要在两个FORM中进行
如楼上的据说
用TstringList代替TypelistBox.Items
 
定义布尔型变量check,然后:
check:=false;
adoquery.sql.Add('select * from table');
for i:=0 to checklistbox.Count-1 do
if checklistbox.Checked then
begin
checked:=true;
break;
end;
if not checked then exit;
adoquery.sql.Add('where');
for i:=0 to checklistbox.Count-1 do
if checklistbox.Checked then
begin
adoquery.sql.Add('col2='+checklistbox.Items.Strings);
adoquery.sql.Add('or');
end;
adoquery.sql.Delete(adoquery.sql.Count-1);
就可以了
 
不知道你的数据库用的是不是Sql Server, 如果是,可以参考以下:

这是SQL server联机从书中的一个例子

SELECT ProductID, ProductName
FROM Northwind.dbo.Products
WHERE CategoryID IN (1, 4, 5)

如果有什么不明白,可以参看联机从书中的“列表搜索条件”
 
一个例子,和楼上的有些类似:
procedure TForm3.FormShow(Sender: TObject);
var
sqlString:String;
I:Integer;
begin
ADOQuery2.SQL.Clear;
sqlString:='select * from Orders where 1=0 ';
for I:=0 to Form1.CheckListBox1.Count-1 do
begin
if Form1.CheckListBox1.Checked then
sqlString:=sqlString+' or OrderID='+''''+Form1.CheckListBox1.Items+'''';
end;
ADOQuery2.SQL.Add(sqlString);
ADOQuery2.Active:=true;
end;
 
顶部