Windows Phone Developers

Sunday, May 1, 2011

How to Bind an Object to TextBox

Binding Objects to Windows Form Controls

Here is a simple example to bind a object to textbox control

Let us have a small form with two Textboxes, a label and a button

We also have a class that has two properties - Name of Company and the Business they are involved. Here is how the class looks

Public Class ClassDataBind

    Private sPrvName As String
    Private sOfferings As String

    Public Sub New(ByVal sName As String, ByVal sOffer As String)
        Me.Name = sName
        Me.Solutions = sOffer
    End Sub

    Property Name() As String

            Return sPrvName
        End Get

        Set(ByVal value As String)
            sPrvName = value
        End Set

    End Property

Let us now Bind the class to the text boxes using

Private Sub FormDataBind_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        oDataBind = New ClassDataBind("Accenture", "Consulting")

        TextBox1.DataBindings.Add("Text", oDataBind, "Name", True, DataSourceUpdateMode.OnPropertyChanged)
        TextBox2.DataBindings.Add("Text", oDataBind, "Solutions", True, DataSourceUpdateMode.OnPropertyChanged)
    End Sub

Once the binding is done , run the code to view how it looks :

Since the text boxes are bound to the Objects and we have set the Objects to be refreshed we can change the contents in textboxes and see if the Objects are refreshed.

Private Sub ButtonClicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = oDataBind.Name + " - " + oDataBind.Solutions
    End Sub

You can now save the object back to DB etc if needed. If you don;t want to update certain field. For example, the company name here - you can do the following: Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment