Binding a custom property to a datatable field ,the source table is changing when navigating through items

385 views Asked by At

I've got custom control inherited from a textbox I added a custom property as follows

Dim _MyVal As Object
Public Property MyVal As Object
    Get
        Return _MyVal
    End Get
    Set(value As Object)
        _MyVal = value
        If IsNothing(value) OrElse IsDBNull(value) Then
            Me.Text = "Null"
        Else
            Select Case _MyVal
                Case 1
                    Me.Text = "NewYork"
                Case 2
                    Me.Text = "London"
                Case 3
                    Me.Text = "Zwara"
                Case Else
                    Me.Text = "Unknown"
            End Select
        End If
    End Set
End Property

So I bound this property to a DataTable field in simple WinForm with a DataGridView and the custom textbox as follows

Public Class Form10

Dim dtMain As New DataTable
Dim bsMain As New BindingSource

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

    dtMain.Columns.Add("Name", GetType(String))
    dtMain.Columns.Add("CityID", GetType(Integer))

    dtMain.Rows.Add("John", 1)
    dtMain.Rows.Add("Steve", 2)
    dtMain.Rows.Add("Sara", 3)
    dtMain.Rows.Add("Joe", DBNull.Value)

    bsMain.DataSource = dtMain
    dgv.DataSource = bsMain

    txtCity.DataBindings.Add(New System.Windows.Forms.Binding("MyVal", bsMain, "CityID", False, DataSourceUpdateMode.OnPropertyChanged))

    dtMain.AcceptChanges()
End Sub

My problems is, when I navigate through items, the DataTable is changed. Why does that happen?

While when I bind the field to a ComboBox SelectedValue property it works perfectly. It doesn't change the source through navigating; it changes when I change the SelectedValue property

0

There are 0 answers