Category Archives: Winform

Highlight specific text in RichTextBox

TextBox is not capable of displaying text with multiple colors. We need to use RichTextBox in order to highlight specific text. The demo code here uses .NET Regular Expression to find the text and highlight them with red color.

Include this reference to use Regex class.

Imports System.Text.RegularExpressions

Highlight 8-digit numbers in the RichTextBox.

Dim regex As New Regex("[0-9]{8}")

For Each matchedText As Match In regex.Matches(Me.RichTextBoxApprovedVoucher.Text)
    Me.RichTextBox1.Select(matchedText.Index, matchedText.Length)
    Me.RichTextBox1.SelectionColor = Color.Red
Leave a comment

Posted by on June 18, 2012 in .NET, VB, Winform


GroupBox Validating event isn’t firing on ValidateChildren call

The Validating event code for GroupBoxes below checks if at lease 1 CheckBoxes checked in the group. It works with Form.AutoValidate enabled. But when Form.ValidateChildren() is called, this validating event isn’t firing.

' Validate if at least 1 of the CheckBoxes in the GroupBox is checked
Private Sub GroupBox_Validating(ByVal sender As System.Object, _
                                ByVal e As System.ComponentModel.CancelEventArgs) _
    Handles GroupBoxStatus.Validating, GroupBoxClass.Validating

    Dim isValid As Boolean = False
    For Each ctrl As Control In DirectCast(sender, Control).Controls
        If TypeOf ctrl Is CheckBox Then
            If DirectCast(ctrl, CheckBox).Checked Then
                isValid = True
                Exit For
            End If
        End If

    If isValid = False Then
        Me.ErrorProvider1.SetError(DirectCast(sender, Control), "Check at least one item")
        e.Cancel = True
        Me.ErrorProvider1.SetError(DirectCast(sender, Control), "")
        e.Cancel = False
    End If

End Sub

Read the rest of this entry »

Leave a comment

Posted by on June 7, 2012 in .NET, VB, Winform


Not to select the first row in DataGridView by default

DataGridView makes the first row selected after DataBinding by default. I tried using DataGridView.ClearSelection() in the Form.Load event to unselect it with no avail. The problem is that data hasn’t been bond to the DataGridView in the Form.Load event. The method should be placed in the DataBindingComplete event of the DataGridView:

Private Sub DataGridView1_DataBindingComplete(ByVal sender As System.Object, _
    ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) _
    Handles DataGridView1.DataBindingComplete

    Dim gridView As DataGridView
    gridView = CType(sender, DataGridView)
End Sub

Reference: C# DataGridView: First row is being selected by default


Posted by on May 14, 2012 in .NET, VB, Winform



How to validate Windows Form user input

Here are a couple notes taken from the MSDN User Input Validation in Windows Forms article.

Where to place the validation logic :
Validating event. If the Control.CausesValidation property is set to false, the Validating and Validated events of that control will not fire.

When does the validating event execute :
1. By Form.AutoValidate property. It specifies whether the control is validated on focus change by the AutoValidate enumerated value. (Implicit validation)
2. By calling Validate or ValidateChildren. (Explicit validation)

How to close the form when validation failed using AutoValidate :
There’s no problem closing the form if AutoValidate is set to Disable or EnableAllowFocusChange. If not, set e.Cancel to false in the Form.Closing event.

Read the rest of this entry »

Leave a comment

Posted by on April 5, 2012 in .NET, VB, Winform



Custom Dialog Box example : ChooseDateDialog

Here’s a complete example on how to show dialog box and retrieve user input. More details on Dialog Box from Dialog Boxes in Windows Forms. The ChooseDateDialog is a simple custom dialog box which is used to prompt for a date. Its functionality is like this:

First, use a simple button to call ChooseDateDialog:

Read the rest of this entry »

Leave a comment

Posted by on April 5, 2012 in .NET, VB, Winform



Why is DataGridView slow

I have an about 100 rows DataGridView which drops performance significantly since I wrote some code modifying its cells value programmatically. After looking up the MSDN post, the property AutoSizeColumnsMode is the reason why my DataGridView being slow. The property was set to AllCells, turns out it’ll auto resize cells when the value changes and that takes a lot of resource.

By 100 rows my code will run for about 1500 milliseconds. Changing the property to DisplayedCells can reduce it to 30 milliseconds and changing to ColumnHeader can reduce it to less than 8 milliseconds. It’ll cost no time if I commented the value changing code.

I guess every single cell value change will always auto resize according to the value of the AutoSize property, even when the property value is ColumnHeader.

Leave a comment

Posted by on March 13, 2012 in .NET, Winform


Tags: , ,

Add a select all checkbox at DataGridView header

These methods put a CheckBox at the first column header of the DataGridView to select/deselect all CheckBoxes in the first column of every DataGridViewRow. The CheckBox at the header also change its state according to the states of the CheckBoxes at each row. To apply it to a DataGridView:
1. Add a DataGridViewCheckBoxColumn as the first column in the DataGridView.
2. Copy the codes into the form.
3. Call AddSelectAllCheckBox with the DataGridView.

Private Sub MyForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub

'This member is necessary to distinqish if the header CheckBox is clicked
'in the CellValueChanged event.
Private _IsSelectAllChecked As Boolean

Private Sub AddSelectAllCheckBox(ByVal theDataGridView As DataGridView)
    Dim cbx As New CheckBox
    cbx.Name = "SelectAll"
    'The box size
    cbx.Size = New Size(14, 14)

    Dim rect As Rectangle
    rect = theDataGridView.GetCellDisplayRectangle(0, -1, True)
    'Put CheckBox in the middle-center of the column header.
    cbx.Location = New System.Drawing.Point(rect.Location.X + ((rect.Width - cbx.Width) / 2), rect.Location.Y + ((rect.Height - cbx.Height) / 2))
    cbx.BackColor = Color.White

    'Handle header CheckBox check/uncheck function
    AddHandler cbx.Click, AddressOf HeaderCheckBox_Click
    'When any CheckBox value in the DataGridViewRows changed,
    'check/uncheck the header CheckBox accordingly.
    AddHandler theDataGridView.CellValueChanged, AddressOf DataGridView_CellChecked
    'This event handler is necessary to commit new CheckBox cell value right after
    'user clicks the CheckBox.
    'Without it, CellValueChanged event occurs until the CheckBox cell lose focus
    'which means the header CheckBox won't display corresponding checked state instantly when user
    'clicks any one of the CheckBoxes.
    AddHandler theDataGridView.CurrentCellDirtyStateChanged, AddressOf DataGridView_CurrentCellDirtyStateChanged
End Sub

Read the rest of this entry »


Posted by on March 5, 2012 in .NET, VB, Winform