You are probaly familiar with .NET's databinding when you are using a DataTable or similar System.Data object. Anyway, let's say that you aren't. Can you still take advantange of .NET's databinding. Well, until today I didn't think there was much you could do. I did know that you could bind to a Strongly typed collection, but this seemed just like the same face of binding to a datatable, after all, isn't it a collection?
Earlier today I was playing with an application and I noticed that when you call the Add method of the Listbox or any other Complexly bound object, the Items property takes type 'Object'. Well in VB6 I seem to remember this being of type string and I was wondering what would be the benefit of adding type object instead when you'd just have to downcast it anyway. I figured it out and the reason is that you don't have to downcast it.
Take the following Object definition:
| Imports System Public Class Customer Private _firstName As String Private _lastName As String Public Property FirstName() As String Get Return _firstName End Get Set(ByVal Value As String) _firstName = Value End Set End Property Public Property LastName() As String Get Return _lastName End Get Set(ByVal Value As String) _lastName = Value End Set End Property Public ReadOnly Property FullName() As String Get Return Me.LastName & ", " & Me.FirstName End Get End Property Public Sub New(ByVal first As String, ByVal last As String) _firstName = first _lastName = last End Sub End Class |
| Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim bill As New Customer("Bill", "Ryan") Dim brian As New Customer("Brian", "Davis") Dim les As New Customer("Lester", "Smith") lb.ValueMember = "FullName" lb.DisplayMember = "FullName" lb.Items.Add(bill) lb.Items.Add(brian) lb.Items.Add(les) End Sub Private Sub lb_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lb.SelectedIndexChanged MessageBox.Show(CType(lb.SelectedItem, Customer).FirstName) End Sub |