Wednesday, April 18, 2012

Winforms ComboBox Text & Value example

the really simple way, and goes for the rest of the winform controls
you could also put a list of any class and choose 2 properties

DataTable tblMonths = new DataTable();
tblMonths.Columns.Add(new DataColumn("Name", typeof(string)));
tblMonths.Columns.Add(new DataColumn("Value", typeof(int)));
for (int i = 1; i <= 12; i++)
{
    string month = DateTimeFormatInfo.CurrentInfo.GetMonthName(i);
    tblMonths.Rows.Add(
    new object[] { month, i });
}
cmbMonths.DataSource = tblMonths;
cmbMonths.ValueMember = "Value";

cmbMonths.DisplayMember = "Name";
cmbMonths.SelectedValue =
DateTime.Now.Month;

No comments:

Post a Comment