简体   繁体   English

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

[英]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 // 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): 由于您已经将所有枚举名称存储在组合框中,因此只需使用其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;
    }
}
cmbHousing.SelectedIndex = 0;

要么

cmbHousing.SelectedItem = housingTypeNames[0];

Use this cmbHousing.SelectedItem = housingTypeNames[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];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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