Plunging into .NET Development

Weblog Pieter Gheysens
Microsoft .NET Development - C# - Enterprise Library - Visual Studio 2005 Team System - Compuware DevPartner - ...
 


Thursday, February 24

Binding combobox to an array

In this sample I will bind an array that contains all months to a combobox. A structure Month will be used instead of a class. A struct type is a value type [a class type is a reference type] that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. The objects of struct types are always created on the stack and struct types are more useful for lightweight data structures that have value semantics.

        private struct Month

        {

            private int monthId;

            private string monthName;

 

            public Month(int monthId, string monthName)

            {

                this.monthId = monthId;

                this.monthName = monthName;

            }

 

            public int MonthId

            {

                get { return this.monthId; }

            }

 

            public string MonthName

            {

                get { return this.monthName; }

            }

        }


A simple private method getMonths is created that returns all months in an a Month-array.

        private Month[] getMonths()

        {

            Month[] months = new Month[]

                { new Month(1, "January"), new Month(2, "February"), new Month(3, "March"),

                    new Month(4, "April"), new Month(5, "May"), new Month(6, "June"),

                    new Month(7, "July"), new Month(8, "August"), new Month(9, "September"),

                    new Month(10, "October"), new Month(11, "November"), new Month(12, "December") };

 

            return months;

        }


Binding has now become simple : set the dataSource of the comboBox to the array and set the DisplayMember and ValueMember.

            this.cmbMonth.DataSource = this.getMonths();

            this.cmbMonth.ValueMember = "MonthId";

            this.cmbMonth.DisplayMember = "MonthName";


When an item is selected in the comboBox, you can retrieve the selected monthId and monthName by casting the SelectedItem to the Month structure.

            Month selectedMonth = (Month) this.cmbMonth.SelectedItem;


1 Comments:

  • At 6:23 AM, Blogger Unknown said…

    Excellent code. But what's the advantage of binding a structure to a combobox? A simple array or combbox1.items.add("added") could have been used to do the same task.

    Aads

     

Post a Comment

<< Home