Board index » delphi » How do you Add Object to TStingGrid.Objects[] ?

How do you Add Object to TStingGrid.Objects[] ?

I'm having trouble using the Objects array of a TStringGrid.  I have a
TString grid that is 4x6, with string in all the cells ( I can see them
on the screen).  I want to store some additional information with each
row, so I thought I'd crate my own object and attach it to the Objects
propery of the cell in column zero.  It compiles, but at runtime I get this:

EStringSparseListError - PutObject to Undefined Item.

Can anyone tell me what I'm doing wrong?  Thanks in advance, CB.

PS: Here's what my code looks like:

type

  TMyClass = class(TObject)
    i:  Integer;
  end;

  TMyForm = class(TForm)
    MessageList: TStringGrid;
    procedure MyMethod;
    ...
  end;

..

procedure TMyForm.MyMethod;
var
    MyClass: TMyclass;

begin  
    MyClass := TMyClass.Create;
    MessageList.Cells[0,1] := 'Something here.';  {works fine}
*   MessageList.Objects[0,1]:=MyClass;            { Fails }
end;

If I stop the de{*word*81} at the *, I see:
  MessageList.RowCount = 2
  MessageList.ColCount = 4
  MessageList.Cells[0,1] = 'Something Here'
  MessageList.Objects[0,1] = Nil
--
============================================================================
   Clark Bremer - Sr. Software Engineer         mailto:cla...@netstar.com
   NetStar Inc.                                    http://www.netstar.com
   10250 Valley View Rd - Minneapolis, MN - 55344      fax:(612) 943-8939

 

Re:How do you Add Object to TStingGrid.Objects[] ?


Michael Vincze Suggested this:

Quote
> You should have:

>  MessageList.AddObject ('Something here.', MyClass);

> in place of:

>>    MessageList.Cells[0,1] := 'Something here.';  {works fine}
>>*   MessageList.Objects[0,1]:=MyClass;            { Fails }

I went back to my real code (as opposed to the sample code) and saw
that I really need to add the object AFTER the string is added, so Michael's
method won't work.  What I discovered after a little messing around was that
the cell I was attaching the object to did exist, but I had not yet set the
string to anything.  I just used a different column of that row that always
has a value in it, and my problem was solved.  

The Moral:  You cannot attach an object to a cell in a TStringGrid until you
have assigned a string to that cell.  Thanks for your help, Michael.  CB.

--
============================================================================
   Clark Bremer - Sr. Software Engineer         mailto:cla...@netstar.com
   NetStar Inc.                                    http://www.netstar.com
   10250 Valley View Rd - Minneapolis, MN - 55344      fax:(612) 943-8939

Other Threads