简体   繁体   中英

Display first value at dropdownlist

Goal:
Automatically display the first value from the enum Housing instead of displaying "white space" in drop down list

Problem:
Don't know how to display the first value of the enum when you initiate the program.

// Fullmetalboy

namespace Assignment1
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }


        private AnimalManager _myAnimalManager;



        private void CreateHousingOptions()
        {
            string[] housingTypeNames = Enum.GetNames(typeof(Housing));
            cmbHousing.Items.Clear();

            for (int rbIndex = 0; rbIndex < housingTypeNames.Length; rbIndex++)
            {
                cmbHousing.Items.Add(housingTypeNames[rbIndex]);
            }

        }



    }
}

namespace Assignment1.HousingType
{

    /// <summary>
    /// 
    /// </summary>
    public enum Housing
    {
        Stable,
        Cage,
        Indoor,
        Outdoor
    }

}

Since you're already storing all the enum names in your combo box, you only have to use its SelectedIndex property in order to select the first item (if it exists):

private void CreateHousingOptions()
{
    cmbHousing.Items.Clear();
    foreach (string housingTypeName in Enum.GetNames(typeof(Housing))) {
        cmbHousing.Items.Add(housingTypeName);
    }
    if (cmbHousing.Items.Count > 0) {
        cmbHousing.SelectedIndex = 0;
    }
}
cmbHousing.SelectedIndex = 0;

要么

cmbHousing.SelectedItem = housingTypeNames[0];

Use this cmbHousing.SelectedItem = housingTypeNames[0];

  private void CreateHousingOptions()
        {
            string[] housingTypeNames = Enum.GetNames(typeof(Housing));
            cmbHousing.Items.Clear();
        for (int rbIndex = 0; rbIndex < housingTypeNames.Length; rbIndex++)
        {
            cmbHousing.Items.Add(housingTypeNames[rbIndex]);
        }

        cmbHousing.SelectedItem = housingTypeNames[0];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM