Create New DBGrid Column at runtime

Hi again,

It's not my day today :o)

I am trying to insert a new Column to a database grid at runtime but get an error "Index out of bounds"

I need this column to replace the current first column. I guess I should be using Insert instead of Add ???

Here is the code:

procedure TForm1.Button4Click(Sender: TObject);
Var
ColumnA : TColumn;
Begin
If DBGrid1.Columns.Count>1 then
begin
DBGrid1.Columns.Insert(DBGrid1.Columns.Count );
ColumnA:=DBGrid1.Columns.Items[DBGrid1.Columns.Count-1];
ColumnA.Title.Caption:='OK';
end
else
begin
ColumnA:= DBGrid1.Columns.Add;
ColumnA.Title.Caption:='OK';
end;
end;

Any ideas?

Thanks

St3VO
ST3VOAsked:
Who is Participating?
 
Martin BarredaLic. in Computer ScienceCommented:
I use something like this...

If SOMEOPTIONISSELECTED then //insert a column in first place
    begin
      grDatos.Columns.Insert(0);
      grDatos.Columns[0].FieldName := 'NAMEOFFIELDTOSHOW';
      grDatos.Columns[0].Alignment := taCenter;
      grDatos.Columns[0].Width     := 60;
      grDatos.Columns[0].Title.Alignment := taCenter;
    end;
if SOMEOTHEROPTIONISSELECTED then //insert a column at the end
    begin
      grDatos.Columns.Add;
      grDatos.Columns[grDatos.Columns.Count-1].FieldName := 'OTHERFIELDTOSHOW';
      grDatos.Columns[grDatos.Columns.Count-1].Alignment := taCenter;
      grDatos.Columns[grDatos.Columns.Count-1].Width     := 60;
      grDatos.Columns[grDatos.Columns.Count-1].Title.Caption   := 'TITLEOFOTHERFIELDTOSHOW';
      grDatos.Columns[grDatos.Columns.Count-1].Title.Alignment := taCenter;
    end;

Hope this help!
0
 
ST3VOAuthor Commented:
Sorry, I modified the code above already :o) I WAS using Insert...hehehe!
0
 
mokuleCommented:
You can simply replace all Your code with

  TColumn(DBGrid1.Columns.Insert(DBGrid1.Columns.Count-1)).Title.Caption := 'OK';
0
 
ST3VOAuthor Commented:
Thanks!!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.