在下拉列表中显示第一个值

时间:2011-02-12 10:01:13

标签: c#

目标:
自动显示枚举外壳中的第一个值,而不是在下拉列表中显示“空格”

问题:
启动程序时,不知道如何显示枚举的第一个值。

// 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
    }

}

3 个答案:

答案 0 :(得分:1)

由于您已经在组合框中存储了所有枚举名称,因此您只需使用其SelectedIndex属性来选择第一个项目(如果存在):

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;
    }
}

答案 1 :(得分:0)

cmbHousing.SelectedIndex = 0;

cmbHousing.SelectedItem = housingTypeNames[0];

答案 2 :(得分:0)

使用此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];
    }