我在開始的C#類,我無法弄清楚爲什麼在下面的代碼運行後,選定的索引仍然是-1(即加載時的組合框爲空)。應該默認爲的selectedIndex = 1:在ComboBox上設置SelectedIndex
public string[,] GetArray()
{
//create array with conversion values
string[,] conversionInfo = { {"Miles","Kilometers", "1.6093"},
{"Kilometers","Miles", ".6214"},
{"Feet","Meters", ".3048"},
{"Meters","Feet","3.2808"},
{"Inches","Centimeters", "2.54"},
{"Centimeters","Inches",".3937"}};
return conversionInfo;
}
private void Form_Load(object sender, EventArgs e)
{
//get array to use
string[,] conversionChoices = GetArray();
//load conversion combo box with values
StringBuilder fillString = new StringBuilder();
for (int i = 0; i < conversionChoices.GetLength(0); i++)
{
for (int j = 0; j < conversionChoices.GetLength(1) - 1; j++)
{
fillString.Append(conversionChoices[i, j]);
if (j == 0)
{
fillString.Append(" to ");
}
}
cboConversion.Items.Add(fillString);
fillString.Clear();
}
//set default selected value for combobox
cboConversion.SelectedIndex = 0;
}
public void cboConversions_SelectedIndexChanged(object sender, EventArgs e)
{
LabelSet(cboConversion.SelectedIndex);
}
public void LabelSet(int selection)
{
//get array to use
string[,] labelChoices = GetArray();
//set labels to coorespond with selection
string from = labelChoices[selection, 0];
string to = labelChoices[selection, 1];
lblFrom.Text = from + ":";
lblTo.Text = to + ":";
}
這是一個課堂作業,所以我不允許使用設計,而不是鏈接的方法來事件的其他設置任何東西。除了組合框的默認值之外,一切正常工作。
你說「它應該默認爲selectedIndex 1」,但是您在代碼中將組合框SelectedIndex設置爲0。 – 2012-03-27 21:05:08
他做得很對,因爲0是列表中的第一個元素。 – 2012-03-27 21:21:15
我知道。寫的問題表明她希望SelectedIndex爲1的項目,而不是列表中的第一個元素,這將是索引0. – 2012-03-28 01:25:56