473,383 Members | 1,877 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,383 developers and data experts.

Binding a ComboBox to a custom collection

It's pretty simple to programmatically add items to a combobox at runtime. Just declare the object, then call ComboBox.Items.Add(...) for each item you wish to add. The one downside to this method is that you cannot specify values for the display member - the text shown in the ComboBox item - and the value member - the value returned when you query the combobox's SelectedValue property.

The simple way round this is to bind the combobox to a collection of objects. When binding a combobox, you specify the source (the collection), the name of the display member and the name of the value member. The names you specify correspond to the names of the properties of the object.

So, we need to create a two classes; one for each item in the combobox, and another generic collection class to group them all together and serve as the data source. Let's get started.

In my example, the item class represents a state. Each state has a long name, and a short name, as used in printed street addresses. The class just contains two properties and a simple constructor.

Expand|Select|Wrap|Line Numbers
  1. Public Class State
  2.     Private _ShortName As String
  3.     Public Property ShortName() As String
  4.         Get
  5.             Return _ShortName
  6.         End Get
  7.         Set(ByVal value As String)
  8.             _ShortName = value
  9.         End Set
  10.     End Property
  11.  
  12.     Private _LongName As String
  13.     Public Property LongName() As String
  14.         Get
  15.             Return _LongName
  16.         End Get
  17.         Set(ByVal value As String)
  18.             _LongName = value
  19.         End Set
  20.     End Property
  21.     Public Sub New(ByVal shortName As String, ByVal longName As String)
  22.         Me.ShortName = shortName
  23.         Me.LongName = longName
  24.     End Sub
  25. End Class
  26.  
Now that the item class is defined, I also need a collection class. By inheriting the CollectionBase class, I can access the inbuilt methods for adding, removing and sorting objects. I can also use the collection class constructor to populate the collection and sort the items.

Expand|Select|Wrap|Line Numbers
  1. Public Class States
  2.     Inherits CollectionBase
  3.     Public Sub New()
  4.         InnerList.Add(New State("QLD", "Queensland"))
  5.         InnerList.Add(New State("NSW", "New South Wales"))
  6.         InnerList.Add(New State("VIC", "Victoria"))
  7.         InnerList.Add(New State("TAS", "Tasmania"))
  8.         InnerList.Add(New State("WA", "Western Australia"))
  9.         InnerList.Add(New State("SA", "South Australia"))
  10.         InnerList.Add(New State("NT", "Northern Territory"))
  11.         InnerList.Add(New State("ACT", "Australian Capital Territory"))
  12.         InnerList.Sort(New StatesComparer)
  13.     End Sub
  14.     Friend Class StatesComparer
  15.         Implements IComparer
  16.         Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
  17.             If TypeOf (x) Is State And TypeOf (y) Is State Then
  18.                 Return DirectCast(x, State).LongName < DirectCast(y, State).LongName
  19.             Else
  20.                 Throw New Exception("Object is not of type State")
  21.             End If
  22.         End Function
  23.     End Class
  24. End Class
  25.  
The child class, StatesComparer, handles the sorting of the items. As each item is a custom class, the method of sorting the items needs to be defined. As the CollectionBase's Innerlist property is an Arraylist, the class used to define the sorting needs to implement the IComparer interface. The sorting class presents just one function to its parent, Compare. The function takes two parameters - two different items in the collection - and returns either true or false depending on whether the first parameter is less than (appears in the collection before) the second parameter.

Now I have my populated and sorted collection of items, all I need to do is to bind my combobox to it. It doesn't really matter where one does this, provided it is called before the combobox is needed.

Expand|Select|Wrap|Line Numbers
  1. Dim comboStates As New ComboBox()
  2. comboStates.DataSource = New States
  3. comboStates.DisplayMember = "LongName"
  4. comboStates.ValueMember = "ShortName"
  5.  
Jun 20 '11 #1
0 15164

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: SammyBar | last post by:
Hi, I'm trying to bind a custom collection class to a data grid, following the guidelines from the article http://msdn.microsoft.com/msdnmag/issues/05/08/CollectionsandDataBinding/default.aspx....
6
by: Omar | last post by:
When I try to databind my comboBox (specifically field "emplcode") to a filled dataset , the contents of the comboBox displays a bunch of "System.Data.DataRowView". I assume the amount of times...
2
by: Shrage Smilowitz | last post by:
I try to create a custom collection which i will then use to databind and its not working. Class Book Public BookName As String Sub New(ByVal lBookName As String) Me.BookName = BookName End...
1
by: Conawapa11 | last post by:
I'm having trouble figuring this problem out and every example out there deals with simple objects within a custom collection. Take this example: public class ComplexClass { private int id;...
1
by: Demetri | last post by:
Someone posted the following back in June and I am now doing the same thing. I'll just paste what was asked and see if anyone can give us an answer: ...
3
by: JimGreen | last post by:
We are designing a WinForm application ( three tiered) There is a debate in our group as to whether we should pass datasets or our custom collections from business layer to the user interface...
0
by: Stephajn Craig | last post by:
I've built a customized collection class that has strongly typed objects in it. I have a collection class called LogEntryCollection with LogEntry objects in it. Each LogEntry object has certain...
1
by: viktor9990 | last post by:
I'm trying to bind a custom collection to an autogenerated datagrid without success. I'm getting this error: DataGrid with id 'DataGrid2' could not automatically generate any columns from the...
6
by: npaulus | last post by:
Hi, DataSets are usually resource heavy. Instead of having to pass them from my middle tier to my presentation layer I was wondering if anyone has developed a custom collection object that is...
4
by: Stuart | last post by:
I hope someone can shed some light on an error I've been experiencing for sometime now, but can no longer continue to ignore :-( I've created a custom entity class which implements IEditableObject....
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.