2
\$\begingroup\$

I have a few columns in a DBGrid that I want to hide and show at different times depending on what the user wants to view.

Rather than writing the following code;

For i := 1 to DBGrid1.Columns.Count -1 do
  Begin

    If DBGrid1.Columns[i].FieldName = 'SOMETHING' then
      Begin
        if DBGrid1.Columns[i].visible then 
        DBGrid1.Columns[i].visible:=false else 
        DBGrid1.Columns[i].visbile:=true;
      End;

    If DBGrid1.Columns[i].FieldName = 'ANOTHERFIELD' then
      Begin
        if DBGrid1.Columns[i].visible then 
        DBGrid1.Columns[i].visible:=false else 
        DBGrid1.Columns[i].visbile:=true;
      End;

    { And so on... for another 8 columns }

  End;
End;

I've got the following function;

Function Flip(CurrentState:Boolean):Boolean;
Begin

  If CurrentState then
     Result:=False else
     Result:=True;

End;

Then I use the function above like this;

For i := 1 to DBGrid1.Columns.Count -1 do
  Begin

    If DBGrid1.Columns[i].FieldName = 'SOMETHING' then
    DBGrid1.Columns[i].visible := Flip(DBGrid1.Columns[Loop].visible;

    If DBGrid1.Columns[i].FieldName = 'ANOTHERFIELD' then
    DBGrid1.Columns[i].visible := Flip(DBGrid1.Columns[Loop].visible;

    { And so on... for another 8 columns }

  End;
End;

I can't address columns by their index directly because they move around, therefore I use the Field Name associated with it.

My question is this, is there are better and smarter way to hide and unhide many columns?

\$\endgroup\$
  • \$\begingroup\$ I'd replace the if-then-elses with DBGrid1.Columns[i].Visible := not DBGrid1.Columns[i].Visible. I.e. use the notkeyword instead of your Flip function. \$\endgroup\$ – Ulrich Gerhardt Jul 5 '16 at 9:00
2
\$\begingroup\$

I'd replace the if-then-elses with DBGrid1.Columns[i].Visible := not DBGrid1.Columns[i].Visible - i.e. use the not keyword instead of your Flip function.

And you probably can store references to the relevant columns in an array, TList or similar. Then you don't need to loop all columns and check their names.

\$\endgroup\$
  • \$\begingroup\$ I had not considered the Not and it works perfectly. The array or List I'm not going to worry about as there are only a dozen fields to loop through. Thanks. \$\endgroup\$ – Admiral Noisey Bottom Jul 6 '16 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.