为什么ListBox在将对象添加到列表后立即返回nil或没有Object?

时间:2012-04-06 20:54:22

标签: object listbox nullreferenceexception delphi-prism

这是system.object:

  TTrendGroup = class(System.Object)
    SigList:ArrayList;
    Rate,Phase,Delay:SmallInt;
    RateIndex,PhaseIndex:SmallInt;
    firstTime:Boolean;
    base:integer;
    Enabled:Boolean;
    name:string;
    public
    constructor;
    method AddTGroup(signal:TTrendSignal);
    method Clear;
    method Poll(list:ArrayList);
    method ReadTGroup(bTGr:BinaryReader);
    method WriteTGroup(bTGw:BinaryWriter);
    method WriteSignals(bWSw:BinaryWriter);
    method ToString:String;override;
  end;

constructor TTrendGroup;
begin
  SigList := new ArrayList;
  Rate := 30;
  Phase := 0;
  Delay := Phase;
  RateIndex := 4;
  PhaseIndex := 0;
  firsttime := true;
  enabled := true;
  name := '';
end;

以下是我如何从上面的system.object创建一个对象并将其添加到我的GroupList ListBox中:

method HTrendFrm.AddGroup1_Click(sender: System.Object; e: System.EventArgs);
var
  i:integer;
  grp:TTrendGroup;
begin
  if ReadWrite then
  begin
    grp := new TTrendGroup;
    grp.name:='New Group';
    i := GroupList.Items.Add(grp);
    GroupList.SelectedIndex := i;
    grpName.Text := 'New Group';
    PollBtn.Checked := grp.Enabled;
    RateBox.SelectedIndex := grp.RateIndex;
    PhaseBox.SelectedIndex:= grp.PhaseIndex;
    SignalListBox.Items.Clear;
    UpdateButtons;
  end;
end;

以下是我尝试检索system.object的方法,我刚刚添加回来:

method HTrendFrm.GroupList_Click(sender: System.Object; e: System.EventArgs);
 var
  grp:TTrendGroup;
begin
  if (GroupList.SelectedIndex = -1) then exit;
  with GroupList do
  begin
    grp := TTrendGroup(items[SelectedIndex]); <<<<< HERE is WHERE THE PROBLEM IS. grp always returns NIL.
  end;
end;

我不知道为什么。我在这个程序的其他部分有非常相似的代码,它们按预期工作。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

当返回的对象为nil时,您确认SelectedIndex值实际上是否有效?您的代码中存在逻辑错误,当ListBox不为空时,{J}允许SelectedIndex-1。您的if语句需要使用or运算符而不是and运算符:

// if (GroupList.Items.Count<=0) and (GroupList.SelectedIndex = -1) then exit;
if (GroupList.Items.Count<=0) or (GroupList.SelectedIndex = -1) then exit;