[英]ComboBox control shows no items
我試圖學習C#的基礎知識,並決定制作一個簡單的Windows窗體來演示Dictionary類,但是當我啟動程序時,盡管我向其中加載了一些數據,但Combo- / ListBox控件仍然為空。 希望你能幫我這個忙。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ClassDictionaryExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Dictionary<string, string[]> CountryList = new Dictionary<string, string[]>();
private void Form1_Load(object sender, EventArgs e)
{
CountryList["Bulgaria"] = new string[] { "Sofia University St Kliment Ohridski", "Technical University of Sofia",
"Plovdiv University Paisii Hilendarski" };
CountryList["Romania"] = new string[] { "Alexandru Ioan Cuza University", "Babes-Bolyai University",
"University of Bucharest" };
CountryList["Serbia"] = new string[] { "University of Belgrade", "University of Novi Sad", "University of Niš" };
foreach (var CountryKey in CountryList.Keys)
{
comboBoxCountry.Items.Add(CountryKey);
}
comboBoxCountry.SelectedIndex = 0;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCountry = comboBoxCountry.SelectedItem.ToString();
if (comboBoxCountry.SelectedIndex == 0)
listBoxUniversities.Items.Clear();
else
{
listBoxUniversities.Items.Clear();
listBoxUniversities.Items.AddRange(CountryList[selectedCountry]);
}
}
}
}
我試圖重現您的問題,但沒有。 您需要記住,必須為代碼分配2個事件。 一個在FormLoaded上,另一個在ComboboxSelectionChanged上。
當所選索引為零時,我已經減少了您的代碼以顯示大學。
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
comboBoxCountry.SelectedIndexChanged += comboBoxCountry_SelectedIndexChanged;
}
private Dictionary<string, string[]> _countryList;
public Dictionary<string, string[]> CountryList
{
get
{
if (_countryList == null)
{
_countryList = new Dictionary<string, string[]>();
_countryList["Bulgaria"] = new string[] { "Sofia University St Kliment Ohridski", "Technical University of Sofia", "Plovdiv University Paisii Hilendarski" };
_countryList["Romania"] = new string[] { "Alexandru Ioan Cuza University", "Babes-Bolyai University", "University of Bucharest" };
_countryList["Serbia"] = new string[] { "University of Belgrade", "University of Novi Sad", "University of Niš" };
}
return _countryList;
}
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (var CountryKey in CountryList.Keys)
comboBoxCountry.Items.Add(CountryKey);
comboBoxCountry.SelectedIndex = 0;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCountry = comboBoxCountry.SelectedItem.ToString();
listBoxUniversities.Items.Clear();
listBoxUniversities.Items.AddRange(CountryList[selectedCountry]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.