How can I access a TDBGrid column by name instead of Index?
For example, now I use:
grdInvoiceItems.Columns[2].Visible := False;
but it would be much better to write something like:
grdInvoiceItems.Columns['UnitPrice'].Visible := False;
In the mean time I use a for cycle like in:
for idx := 0 to grdInvoiceItems.Columns.Count - 1 do
begin
if (
(grdInvoiceItems.Columns[idx].FieldName = 'UnitPrice') or
(grdInvoiceItems.Columns[idx].FieldName = 'Discount') or
(grdInvoiceItems.Columns[idx].FieldName = 'SecretCode')
) then
grdInvoiceItems.Columns[idx].Visible := False;
end;
Using colum name is IMO much better tham column index since index is subject to change more often than name.
Any idea on how to encapsulate it better?
You could try something like this:
function ColumnByName(Grid : TDBGrid; const AName : String) : TColumn;
var
i : Integer;
begin
Result := Nil;
for i := 0 to Grid.Columns.Count - 1 do begin
if (Grid.Columns[i].Field <> Nil) and (CompareText(Grid.Columns[i].FieldName, AName) = 0) then begin
Result := Grid.Columns[i];
exit;
end;
end;
end;
Of course, if you are using a version of Delphi which is recent enough to support Class Helper
s, you could wrap this function into a Class Helper
for TDBGrid
, like this
type
TGridHelper = class helper for TDBGrid
function ColumnByName(const AName : String) : TColumn;
end;
[...]
function TGridHelper.ColumnByName(const AName: String): TColumn;
var
i : Integer;
begin
Result := Nil;
for i := 0 to Columns.Count - 1 do begin
if (Columns[i].Field <> Nil) and (CompareText(Columns[i].FieldName, AName) = 0) then begin
Result := Columns[i];
exit;
end;
end;
end;
Then, you could do this
Col := DBGrid1.ColumnByName('SomeName');
Obviously, you could write a similar function which searches by the column's title, rather than the associated Field's FieldName.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With