C# 在组合框上设置SelectedIndex
我在一个初级C类中,我很难弄清楚为什么在以下代码运行之后,所选索引仍然是-1,即加载时的组合框是空的。它应该默认为selectedIndex=1:C# 在组合框上设置SelectedIndex,c#,winforms,C#,Winforms,我在一个初级C类中,我很难弄清楚为什么在以下代码运行之后,所选索引仍然是-1,即加载时的组合框是空的。它应该默认为selectedIndex=1: public string[,] GetArray() { //create array with conversion values string[,] conversionInfo = { {"Miles","Kilometers", "1.6093"},
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(项目列表中项目的索引)和文本(组合框中显示的文本)之间有所不同。因此,请考虑何时以及如何设置ComboBox的Text属性 更改后,始终将“文本”属性设置为项目列表的第一个值
问候,马里奥的回答也可以解释为:
将代码放在加载后示例:在显示的事件中,控件以这种方式初始化并包含项。您说它应该默认为selectedIndex 1,但您在代码中将组合框selectedIndex设置为0。他做得对,因为0是列表的第一个元素。我知道这一点。书面问题表示她希望项目位于SelectedIndex 1,而不是列表中的第一个元素,即索引0。感谢您的回复!我添加了这一行cboConversion.Text=conversionChoices[0,0]+到+conversionChoices[0,1];在表单加载方法的底部,它现在正在工作。我很感激你不仅给我代码,而且还解释了原因,这真的很有帮助,因为我还在学习。