473,326 Members | 2,732 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Binding controls to custom classes

I have a question about simple binding:
(please forgive any syntax errors... I am at home, where I do not have
Vb.Net installed, and I rely far too much on Vb's intellisense!)

If I have two textboxes, Textbox1 and Textbox2, and add a databinding to
Textbox2 as such:

Textbox2.Databindings.Add("Text",Textbox1,"Text")

Anything typed into Textbox1 is mirrored in Textbox2.

Now suppose I want to bind the text property of Textbox2 to a property in a
class that I've written:

Class TestClass
Private m_StringValue as String

Public Property StringValue() as String
Get
Return m_StringValue
End Get
Set(Value as String)
m_StringValue = Value
End Set
End Property

Sub New(InitialValue as String)
m_StringValue = InitialValue
End Sub
End Class

Running the following code does not produce the results I would expect:

Sub Main
Dim MyClass as New TestClass("Test")
TextBox2.SetDataBindings("Text",MyClass,"StringVal ue")
MyClass.StringValue = "New Test"
End Sub

The Text property of Textbox2 at the end of this code fragment is still
"Test", not "New Test"

Do I need to implement any interfaces to cause the changes to the
StringValue property to propogate up to the bound textbox?

Thanks in advance!

Scott Mueller
Sc**********@sbcglobal.net
Nov 20 '05 #1
6 11143
Hi Scott,

Dim oBind As Binding ' (sTargetProperty, oDataSource, sSourceMember)
oBind = New Binding ("Text", oMyClass, "MyClassProperty")
TextBox2.DataBindings.Add (oBind)

I never knew that two TextBoxes could be tied together. So thanks, you've
opened up a new avenue of enquiry. :-)

I haven't got very far but the blurb for Class Binding says:
You can specify an instance of any of the following classes for the
data source:
DataSet, DataTable, DataView, DataViewManager
Any class that implements the IList interface. (or IBindingList,
ITypedList)
Any class. [Though contradicted by Binding Class overview]

As usual the examples are over simplistic and don't tell how to roll your
own. :-(

There's a prototype IList below to save you some typing. ;-)

I've got as far as
TextBox2.DataBindings.Add (New Binding ("Text", oSrc, "Foo"))
But I get an ArgumentException. and no information about what argument or
to what.

Over to you. Scott!! Come back with any progress? ;-)

Regards,
Fergus

<code>
Public Class BindableClass : Implements IList
Private alList As New ArrayList
'-----------------------------------------------------------------
Overridable OverLoads ReadOnly _
Public Property IsFixedSize As Boolean _
Implements IList.IsFixedSize
Get
Return True
End Get
End Property
'-----------------------------------------------------------------
Overridable OverLoads ReadOnly _
Public Property IsReadOnly As Boolean _
Implements IList.IsReadOnly
Get
Return True
End Get
End Property
'-----------------------------------------------------------------
Overridable OverLoads ReadOnly _
Public Property Count As Integer _
Implements ICollection.Count
Get
Return 0
End Get
End Property
'-----------------------------------------------------------------
Overridable OverLoads ReadOnly _
Public Property IsSynchronized As Boolean _
Implements ICollection.IsSynchronized
Get
Return True
End Get
End Property
'-----------------------------------------------------------------
Overridable OverLoads Default _
Public Property Item (ByVal Index As Integer) As Object _
Implements IList.Item
Get
Return alList (Index)
End Get
Set
End Set
End Property
'-----------------------------------------------------------------
Overridable OverLoads ReadOnly _
Public Property SyncRoot As Object _
Implements ICollection.SyncRoot
Get
Return Nothing
End Get
End Property
'-----------------------------------------------------------------
Public Overridable OverLoads Function Add (ByVal Value As Object) _
As Integer Implements IList.Add
Return alList.Add (Value)
End Function
'-----------------------------------------------------------------
Overridable OverLoads _
Public Sub Clear Implements IList.Clear
End Sub
'-----------------------------------------------------------------
Overridable OverLoads _
Public Sub CopyTo (aArray As Array, Index As Integer) _
Implements ICollection.CopyTo
End Sub
'-----------------------------------------------------------------
Overridable OverLoads _
Public Function Contains (ByVal Value As Object) As Boolean _
Implements IList.Contains
End Function
'-----------------------------------------------------------------
Overridable OverLoads _
Public Function GetEnumerator As IEnumerator _
Implements ICollection.GetEnumerator
End Function
'-----------------------------------------------------------------
Overridable OverLoads _
Public Function IndexOf (ByVal Value As Object) As Integer _
Implements IList.IndexOf
End Function
'-----------------------------------------------------------------
Overridable OverLoads _
Public Sub Insert (ByVal Index As Integer, ByVal Value As Object) _
Implements IList.Insert
End Sub
'-----------------------------------------------------------------
Overridable OverLoads _
Public Sub Remove (ByVal Value As Object) _
Implements IList.Remove
End Sub
'-----------------------------------------------------------------
Overridable OverLoads _
Public Sub RemoveAt (ByVal Index As Integer) _
Implements IList.RemoveAt
End Sub
End Class
</code>
Nov 20 '05 #2
Everything that I have read or coded regarding data binding (which is more
than I ever wanted to know) tells me that binding is really one way. It's
meant to work from the user interface to the datasource only and not the
other direction. Near as I can tell, this is because the binding manager
knows when the control changes by the validate event, but has no way of
knowing when the custom class changes. I have even tried to do work arounds
by refreshing the bindings or calling a EndCurrentEdit on the Binding
Manager (this used to refresh the data in VB6). Aside from rebinding the
data, I have yet to find a way to update the control when the datasource
changes.

--

Dean
"Scott Mueller" <Sc**************@aol.com> wrote in message
news:bk************@ID-150716.news.uni-berlin.de...
I have a question about simple binding:
(please forgive any syntax errors... I am at home, where I do not have
Vb.Net installed, and I rely far too much on Vb's intellisense!)

If I have two textboxes, Textbox1 and Textbox2, and add a databinding to
Textbox2 as such:

Textbox2.Databindings.Add("Text",Textbox1,"Text")

Anything typed into Textbox1 is mirrored in Textbox2.

Now suppose I want to bind the text property of Textbox2 to a property in a class that I've written:

Class TestClass
Private m_StringValue as String

Public Property StringValue() as String
Get
Return m_StringValue
End Get
Set(Value as String)
m_StringValue = Value
End Set
End Property

Sub New(InitialValue as String)
m_StringValue = InitialValue
End Sub
End Class

Running the following code does not produce the results I would expect:

Sub Main
Dim MyClass as New TestClass("Test")
TextBox2.SetDataBindings("Text",MyClass,"StringVal ue")
MyClass.StringValue = "New Test"
End Sub

The Text property of Textbox2 at the end of this code fragment is still
"Test", not "New Test"

Do I need to implement any interfaces to cause the changes to the
StringValue property to propogate up to the bound textbox?

Thanks in advance!

Scott Mueller
Sc**********@sbcglobal.net

Nov 20 '05 #3
Hi Dean,

The example that Scott gave of two textboxes tied together - type into one
and the characters appear in both - shows that a Control is capable of being
both source and destination - unless there is some intermediate doing the job.

Perhaps it's too soon to give up hope? :-)

I would hope that there are events that the custom class can raise to
say - here's some more data. Lack of decent documentation is a big problem
here.

Regards,
Fergus
Nov 20 '05 #4
Good point. You are correct Fergus. Although I would argue that I am not
totally mistaken. Given the example of the two texboxes, one updates only
after loosing focus (actually the validate event) and the other updates as
you type. It would seem to me that if it truly was meant to be two way,
then they would both behave the same. Of course it is also entirely
possible that it was meant to be two way and it just happens to have bugs.
:)

By the way, to achieve the same behavior on both textboxes, you have to bind
each to the other.

Also, keep in mind that this is a very simple example of binding. Other
examples using different types of objects require a lot more work to get the
same behavior. Controls to custom data classes can be cumbersome. Again, I
would think that it would work without work around code if it was truly two
way.

If anyone finds a simple answer, I would love to rewrite some code. :)

--

Dean
"Fergus Cooney" <fi******@tesco.net> wrote in message
news:eB**************@TK2MSFTNGP11.phx.gbl...
Hi Dean,

The example that Scott gave of two textboxes tied together - type into one and the characters appear in both - shows that a Control is capable of being both source and destination - unless there is some intermediate doing the job.
Perhaps it's too soon to give up hope? :-)

I would hope that there are events that the custom class can raise to
say - here's some more data. Lack of decent documentation is a big problem
here.

Regards,
Fergus

Nov 20 '05 #5
Actually, Dean, the second textbox does change as you type... at least for
me. It appears to me that the a "property changed" notification is sent by
the OnTextChange method of the TextBox. Here's another interesting twist...
Take the following code:

Sub Main
Dim MyClass as New TestClass("Test")
TextBox2.SetDataBindings(New Binding("Text",MyClass.StringValue,""))
MyClass.StringValue = "New Test"
End Sub
Class TestClass
Private m_StringValue as String

Public Property StringValue() as String
Get
Return m_StringValue
End Get
Set(Value as String)
m_StringValue = Value
End Set
End Property

Sub New(InitialValue as String)
m_StringValue = InitialValue
End Sub
End Class

Running this code produces a textbox with the text set to "Test"

Now alter TestClass to look like this:

Class TestClass
Private m_StringValue as String
Public Event StringValueChanged(e As PropertyChangedEventArgs)
Public Property StringValue() as String

Get
Return m_StringValue
End Get
Set(Value as String)
m_StringValue = Value
RaiseEvent StringValueChanged(New PropertyChangedEventArgs("StringValue"))
End Set
End Property

Sub New(InitialValue as String)
m_StringValue = InitialValue
End Sub
End Class
Run the program now, and TextBox2.SetDataBindings(New
Binding("Text",MyClass.StringValue,"")) throws an exception.

Getting warm?

"Dean Sharp" <de***@insystusa.com> wrote in message
news:ey**************@tk2msftngp13.phx.gbl...
Good point. You are correct Fergus. Although I would argue that I am not
totally mistaken. Given the example of the two texboxes, one updates only
after loosing focus (actually the validate event) and the other updates as
you type. It would seem to me that if it truly was meant to be two way,
then they would both behave the same. Of course it is also entirely
possible that it was meant to be two way and it just happens to have bugs.
:)

By the way, to achieve the same behavior on both textboxes, you have to bind each to the other.

Also, keep in mind that this is a very simple example of binding. Other
examples using different types of objects require a lot more work to get the same behavior. Controls to custom data classes can be cumbersome. Again, I would think that it would work without work around code if it was truly two way.

If anyone finds a simple answer, I would love to rewrite some code. :)

--

Dean
"Fergus Cooney" <fi******@tesco.net> wrote in message
news:eB**************@TK2MSFTNGP11.phx.gbl...
Hi Dean,

The example that Scott gave of two textboxes tied together - type into
one
and the characters appear in both - shows that a Control is capable of being
both source and destination - unless there is some intermediate doing

the job.

Perhaps it's too soon to give up hope? :-)

I would hope that there are events that the custom class can raise

to say - here's some more data. Lack of decent documentation is a big problem here.

Regards,
Fergus


Nov 20 '05 #6
You will have to Implement INotifyPropertyChanged on your bound class.

Imports System.ComponentModel

Public Class Form1

Private iDemoCustomer As DemoCustomer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

iDemoCustomer = DemoCustomer.CreateNewCustomer()
iDemoCustomer.CompanyName = "Company 1"
iDemoCustomer.PhoneNumber = "One One Two One"

Me.TextBox1.DataBindings.Add("Text", iDemoCustomer, "CompanyName")

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

iDemoCustomer.CompanyName = "New Company"

End Sub


'From http://msdn2.microsoft.com/en-us/lib...ed(d=ide).aspx

' This class implements a simple customer type
' that implements the IPropertyChange interface.

Public Class DemoCustomer
Implements INotifyPropertyChanged
' These fields hold the values for the public properties.
Private idValue As Guid = Guid.NewGuid()
Private customerName As String = String.Empty
Private companyNameValue As String = String.Empty
Private phoneNumberValue As String = String.Empty

Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged


Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub

' The constructor is private to enforce the factory pattern.
Private Sub New()
customerName = "no data"
companyNameValue = "no data"
phoneNumberValue = "no data"

End Sub


' This is the public factory method.
Public Shared Function CreateNewCustomer() As DemoCustomer
Return New DemoCustomer()

End Function

' This property represents an ID, suitable
' for use as a primary key in a database.
Public ReadOnly Property ID() As Guid
Get
Return Me.idValue
End Get
End Property


Public Property CompanyName() As String
Get
Return Me.companyNameValue
End Get

Set(ByVal value As String)
If Not (value = companyNameValue) Then
Me.companyNameValue = value
NotifyPropertyChanged("CompanyName")
End If
End Set
End Property


Public Property PhoneNumber() As String
Get
Return Me.phoneNumberValue
End Get

Set(ByVal value As String)
If Not (value = phoneNumberValue) Then
Me.phoneNumberValue = value
NotifyPropertyChanged("PhoneNumber")
End If

End Set
End Property
End Class

End Class

Now to figure out how to make this work for items in a ComboBox....
Jun 29 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Saix News | last post by:
hi, i have a dataset and a number of controls that are bound to it. some of the records being displayed are numerical and are bound to text boxes. they display without a problem but i would...
1
by: rufus | last post by:
Hi, i am relatively new to dotnet and am working on a project that requires me to bind to objects instead of datasets. The reason for this is that we are using an OR mapper to generate these...
1
by: Antero | last post by:
I'm desperate! :-/. I'm desperately trying to bind to objects together to share same data and to display it in a windows forms. I'm trying to bind an custom object to custom control property. I...
0
by: kaborka | last post by:
I've used the Designer to create a strongly typed Dataset class from a stored procedure definition. I called this class cMyDSraw, and the table within it is called MyTable. The Designer...
1
by: Joe Jax | last post by:
I'm building my own version of a readonly DataTable, which needs to bind to various controls. My data table class has two main collections (CollectionBase instances): one of columns, one of rows,...
1
by: matty.hall | last post by:
There's a lot of information out there about data-binding UI objects (i.e. derived from Control) to non-UI custom business objects. Is it possible to do the same without any UI being involved at...
3
by: Steve Gagliardo | last post by:
I am developing a series of custom controls which get added to a parent aspx container using the instruction this.Controls.Add( myControl ). The parent application creates an html table...
19
by: Larry Lard | last post by:
In the old days (VB3 era), there was a thing called the Data Control, and you could use it to databind controls on forms to datasources, and so (as the marketing speak goes), 'create database...
15
by: rizwanahmed24 | last post by:
Hello i have made a custom control. i have placed a panel on it. I want this panel to behave just like the normal panel. The problem i was having is that the panel on my custom control doesnt...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.