Thursday, July 11, 2013

VB6 DataGrid - Auto Height DropDown DataGrid

Dengan mengetahui tinggi item sebuah ListBox seperti yang telah dijelaskan pada posting sebelumnya, maka ada banyak sekali variant code yang bermanfaat yang bisa dikembangkan, salah satunya adalah mengatur tinggi dropdown datagrid secara otomatis. Hal ini sebenarnya bukan masalah apabila item yang terdapat pada ListBox jumlahnya tetap Anda dapat mengatur tinggi ListBoxnya secara manual, tetapi bagaimana jika dinamis? terkadang 1 item, 2 item, 5 item, dsb.  Jangan sampai terjadi seperti gambar di bawah ini:

VB6 NO Auto Heigh Dropdown ListBox DataGrid
Gambar - DropDown DataGrid tanpa Auto Heigh

Padahal tinggi DropDown ListBox seharusnya seperti gambar di bawah ini:

VB6 Drop Down Datagrid
Gambar - DropDown DataGrid dengan Auto Height

Option Explicit 

'------------------------------------------------------------------------------------------ '
'http://khoiriyyah.blogspot.com
'------------------------------------------------------------------------------------------
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByRef lParam As Any) As Long
Private Const
LB_GETITEMRECT As Long = &H198

Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End
Type

Private Declare Function GetSystemMetrics Lib "user32.dll" (ByVal nIndex As Long) As Long

Private Const SM_CXBORDER = 5 'flat
Private Const SM_CYBORDER = 6 'flat
Private Const SM_CXEDGE = 45 '3D
Private Const SM_CYEDGE = 46 '3D

Private Function ListBoxItemHeight(lst As ListBox) As Integer
Dim rc As RECT, I As Long, dy As Long
If lst.ListCount = 0 Then Exit Function
SendMessage lst.hWnd, LB_GETITEMRECT, ByVal 0&, rc
dy = rc.Bottom - rc.Top
ListBoxItemHeight = (dy * Screen.TwipsPerPixelY)
End Function

Private Sub cmdTest_Click()
List1.Visible = False
List1.AddItem "A"
Dim BorderHeight As Integer
If List1.ListCount > 8 Then
List1.Visible = True
Exit Sub
End If
If List1.Appearance = 0 Then 'flat
        BorderHeight = (GetSystemMetrics(SM_CXBORDER) * Screen.TwipsPerPixelX) + (GetSystemMetrics(SM_CYBORDER) * Screen.TwipsPerPixelY)
ElseIf List1.Appearance = 1 Then '3D
        BorderHeight = (GetSystemMetrics(SM_CXEDGE) * Screen.TwipsPerPixelX) + (GetSystemMetrics(SM_CYEDGE) * Screen.TwipsPerPixelY)
End If
List1.Height = (ListBoxItemHeight(List1) * List1.ListCount) + BorderHeight
Debug.Print ListBoxItemHeight(List1)
Debug.Print List1.Height
List1.Visible = True
End Sub