Thursday, May 16, 2013

Grid Dynamic Property via a Method way

Usage of Dynamic Properties of a Grid seems to still baffles others because the sample that we can gleam in case of DynamicBackColor when using the Grid Builder using Ledger Style is via the IIF() condition.

Something like this:

This.Grid1.Column1.DynamicBackColor = ;
      'IIF(MOD(RECNO(),2)=1,RGB(255,255,255),RGB(192,220,192))'

And so by looking at that sample, we can create some more conditions like this:

This.Grid1.Column1.DynamicBackColor = ;
      'IIF(fld1= 1,RGB(255,255,255),RGB(192,220,192))'


So the natural instinct of some developers is that when the need is based on more than two conditions, they would expand above conditions with additional IIF()

This.Grid1.Column1.DynamicBackColor = ;
      'Iif(fld1= 1,Rgb(255,255,255),Iif(fld2 = 2,Rgb(255,255,0),;
           Rgb(192,220,192)))'

Or in case of higher VFP versions that support this, an ICASE() condition:

This.Grid1.Column1.DynamicBackColor = ;
      'ICASE(fld1= 1,Rgb(255,255,255),fld2 = 2,Rgb(255,255,0),Rgb(192,220,192)))'


But what if you have 10 conditions or more?  What if you have 50?  That would be a very long IIF() or ICASE() wouldn't it?  Well, this post is about showing an alternative way of achieving that which is via a Form Method.  Instead of that very long IIF() or ICASE() conditions, we can create a method and put the conditions there via DO CASE... ENDCASE conditions.  Here is a sample of that:



loTest = Createobject("Sample")
loTest.Show(1)

Define Class Sample As Form
      Caption = 'DynamicBackColor via Method'

      Add Object grid1 As Grid

      Procedure Load
            Create Cursor junk (fld1 i)
            Insert Into junk Values (1)
            Insert Into junk Values (2)
            Insert Into junk Values (3)
            Insert Into junk Values (4)
            Insert Into junk Values (2)
            Insert Into junk Values (1)
            Insert Into junk Values (3)
            Insert Into junk Values (1)

            Go Top
      Endproc

      Procedure grid1.Init
            With This
                  .RecordSourceType =1
                  .RecordSource = 'junk'
                  .SetAll('DynamicBackColor','Thisform._ChangeColor()','Column')
            Endwith
      Endproc

      Procedure _ChangeColor
            Local lcColor
            Do Case
                  Case fld1 = 1
                        lcColor = Rgb(255,255,0)
                  Case fld1 = 2
                        lcColor = Rgb(235,235,0)
                  Case fld1 = 3
                        lcColor = Rgb(225,225,0)
                  Case fld1 = 4
                        lcColor = Rgb(245,215,0)
                  Otherwise
                        lcColor = Rgb(255,255,255)
            Endcase
            Return (m.lcColor)
      Endproc
Enddefine

And there you have it.  A much easily readable condition using a form method and DO CASE... ENDCASE.  Hope this helps.  Cheers!

No comments:

Post a Comment