Binding combobox to an array
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, 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