我在开始的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