回 帖 发 新 帖 刷新版面

主题:请教高手

我想把listbox里面的(假如)2条记录,添加到数据库中去
执行时,错误出现在红色字体部分
错误“list index out of bounds(2)"

procedure Tchangeform.BitBtn5Click(Sender: TObject);
var i:integer;
    str1,xh:string;//xh学号
    xm:string;//xm姓名
begin
   i:=listbox2.Items.Count;//listbox2里面的记录数
   if listbox2.Items.Text='' then showmessage('请先选择符合条件的人');
   if messagedlg('确认添加这'+inttostr(i)+'条记录吗?',mtconfirmation,[mbyes,mbno],0)=mryes then
   begin
   [color=FF0000]xm:=listbox2.Items[i];[/color]//把里面的姓名赋给xm
   str1:='update t_info set zt="2" where xm="'+xm+'" ';//更新表t_info
   for i:=0 to listbox2.Items.Count-1 do//循环把值添加到数据库中
   begin
     with tquery.Create(nil) do
     begin
     try
     close;
     databasename:='dbdemos';
     sql.Clear;
     sql.Add(str1);
     prepare;
     execsql;
     sql.Clear;
     sql.Add('select xh from t_info where xm="'+xm+'"');//查询出学号
     xh:=fieldbyname('xh').AsString;把学号赋值给xh
     sql.Add('insert into t_process values(:xh,"2",:fzsj)');//添加记录到表t_process
     parambyname('xh').AsString:=xh;
     parambyname('fzsj').AsDateTime:=datetimepicker1.DateTime;
     finally
     free;
     end;
     end;
     showmessage('成功转为预备党员!');
     listbox2.Items.Clear;
   end;
   end;
end;

回复列表 (共4个回复)

沙发

错误“list index out of bounds(2)" //这是列表项超出范围的错误

   i:=listbox2.Items.Count;//listbox2里面的记录数
   ...
   xm:=listbox2.Items[i];//列表项从0记数至最大为i-1,i值超出范围,所以出错
 

板凳

在delphi中,循环变量是没有初始值d的,只会在循环中赋值,因此,执行到这里时,i会为一个很大的整数,因此会出错。
把这条语句换个地方吧

3 楼

sorry,刚才没看清楚,不好意思!

4 楼

呵呵!

我来回复

您尚未登录,请登录后再回复。点此登录或注册