Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleMake a grid of checks without using CheckBox controls
Keywordscheck box, CheckBox, grid
CategoriesControls
 
Draw the boxes on a PictureBox. In the PictureBox's MouseUp event handler, toggle the boxes' states and draw an X in them if appropriate.
 
Private Const BOX_WID = 20
Private Const NUM_ROWS = 10
Private Const NUM_COLS = 15
Private Const GAP = 8

Private m_BoxChecked(0 To NUM_ROWS - 1, 0 To NUM_COLS - 1) _
    As Boolean

' Draw the original boxes.
Private Sub Form_Load()
Dim r As Integer
Dim c As Integer
Dim X As Single
Dim Y As Single

    ScaleMode = vbPixels
    Picture1.AutoRedraw = True
    Picture1.BorderStyle = vbBSNone
    Picture1.ScaleMode = vbPixels
    Picture1.Move 0, 0, _
        (BOX_WID + GAP) * NUM_COLS + GAP, _
        (BOX_WID + GAP) * NUM_ROWS + GAP
    Width = Width - ScaleX(ScaleWidth, vbPixels, vbTwips) + _
        ScaleX(Picture1.Width, vbPixels, vbTwips)
    Height = Height - ScaleY(ScaleHeight, vbPixels, _
        vbTwips) + ScaleY(Picture1.Height, vbPixels, _
        vbTwips)
    Picture1.FillColor = Picture1.BackColor

    Y = GAP
    For r = 0 To NUM_ROWS - 1
        X = GAP
        For c = 0 To NUM_COLS - 1
            Picture1.Line (X, Y)-Step(BOX_WID, BOX_WID), , B
            X = X + BOX_WID + GAP
        Next c
        Y = Y + BOX_WID + GAP
    Next r
End Sub

' Toggle a box's state.
Private Sub Picture1_MouseUp(Button As Integer, Shift As _
    Integer, X As Single, Y As Single)
Dim r As Integer
Dim c As Integer

    ' See which box this is.
    If Y < GAP Then Exit Sub
    r = (Y - GAP) \ (BOX_WID + GAP)
    If (r < 0) Or (r >= NUM_ROWS) Then Exit Sub
    If Y > GAP + r * (BOX_WID + GAP) + BOX_WID Then Exit Sub

    If X < GAP Then Exit Sub
    c = (X - GAP) \ (BOX_WID + GAP)
    If (c < 0) Or (c >= NUM_COLS) Then Exit Sub
    If X > GAP + c * (BOX_WID + GAP) + BOX_WID Then Exit Sub

    m_BoxChecked(r, c) = Not m_BoxChecked(r, c)
    If m_BoxChecked(r, c) Then
        Picture1.Line (GAP + c * (BOX_WID + GAP), GAP + r * _
            (BOX_WID + GAP))-Step(BOX_WID, BOX_WID)
        Picture1.Line (GAP + c * (BOX_WID + GAP), GAP + r * _
            (BOX_WID + GAP) + BOX_WID)-Step(BOX_WID, _
            -BOX_WID)
    Else
        Picture1.Line (GAP + c * (BOX_WID + GAP) + 1, GAP + _
            r * (BOX_WID + GAP) + 1)-Step(BOX_WID - 2, _
            BOX_WID - 2), Picture1.BackColor, BF
    End If
End Sub
 
My book Custom Controls Library shows how to turn techniques like this into easy-to-use ActiveX controls.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated