Tuesday, December 14, 2004

Enable/Disable databound controls automatically

Here's an easy way to automatically enable/disable databound controls when the CurrencyManager's position changes from/to -1:

Private Sub CmCustomer_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmCustomer.PositionChanged
  If CmCustomer.Position = -1 Then
    Me.DisableDataControls(CmCustomer)
  Else
    Me.EnableDataControls(CmCustomer)
  End If
End Sub

Private _controlEnabledState As Hashtable

Private Sub EnableDataControls(ByVal cm As CurrencyManager)
  For Each b As Binding In cm.Bindings
    EnableControl(b.Control)
  Next
End Sub

Private Sub DisableDataControls(ByVal cm As CurrencyManager)
  For Each b As Binding In cm.Bindings
    DisableControl(b.Control)
  Next
End Sub

Private Sub DisableControl(ByVal c As Control)
  If (_controlEnabledState Is Nothing) Then
    _controlEnabledState = New Hashtable
  End If

  If Not (_controlEnabledState.Contains(c)) Then
    _controlEnabledState.Add(c, c.Enabled)
  End If

  If c.Enabled Then c.Enabled = False
End Sub

Private Sub EnableControl(ByVal c As Control)
  If Not (_controlEnabledState Is Nothing) Then
    If (_controlEnabledState.Contains(c)) Then
      If Not c.Enabled Then c.Enabled = DirectCast(_controlEnabledState(c), Boolean)
      _controlEnabledState.Remove(c)
    End If
  End If
End Sub
 

No comments: