How to throw and catch an exception in the property set when property is bound to a wiform control

  • Thread starter Thread starter Keith Roe
  • Start date Start date
K

Keith Roe

I'm binding the 'Name' property of my object to the 'text' property of a
text box as follows:

txtName.DataBindings.Add(propertyName:="Text", dataSource:=obj,
dataMember:=pi.Name)

When the Property Set of the object is called I am attempting to throw an
exception as follows:

Public Property Name() As String
Get
Return mName
End Get
Set(ByVal Value As String)
If Value.Length > 2 Then
Throw New Exception(Message:="Region 'Name' cannot be
greater than 50 characters")
End If

mName = Value

mDirty = True
End Set
End Property

How do I get a handle on the call to the set statement in order to catch the
exception and display a message to the user? Right now if the user enters
more than 50 characters and presses the save button the excpetion is going
somewhere (I can't figure out where) and the user is unable to close the
form without correcting the entry.
 
Asssuming a spherical cow ... Here is a class that has your property:

Public Class Customer

Private mName As String
Private mDirty As Boolean

Public Property Name() As String
Get
Return mName
End Get
Set(ByVal Value As String)
If Value.Length > 2 Then
Throw New Exception(Message:="Region 'Name' cannot" & _
" be greater than 50 characters")
End If

mName = Value

mDirty = True
End Set
End Property

End Class

The form has a TextBox1 and a Button1. Here is the button click event:

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cust As New Customer

Try
cust.Name = TextBox1.Text
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
End Sub

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

**********************************************************************
Think Outside the Box!
**********************************************************************
 
The problem as stated is that the cow uses databinding. When the TextBox1
is bound (TextBox1.DataBindings.Add(propertyName:="Text", dataSource:=obj,
dataMember:="Name") is where I'm having problem intercepting the thrown
exception. Any thoughts?
 
Back
Top