Display first value at dropdownlist
Goal:
Automatically display the first value from the enum Housing instead of displaying "white space" in drop down listProblem:
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.Len开发者_如何转开发gth; 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;
}
}
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];
}
cmbHousing.SelectedIndex = 0;
or
cmbHousing.SelectedItem = housingTypeNames[0];
精彩评论