2012-03-27 91 views
1

我在开始的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 + ":"; 
    } 

这是一个课堂作业,所以我不允许使用设计,而不是链接的方法来事件的其他设置任何东西。除了组合框的默认值之外,一切正常工作。

+0

你说“它应该默认为selectedIndex 1”,但是您在代码中将组合框SelectedIndex设置为0。 – 2012-03-27 21:05:08

+0

他做得很对,因为0是列表中的第一个元素。 – 2012-03-27 21:21:15

+0

我知道。写的问题表明她希望SelectedIndex为1的项目,而不是列表中的第一个元素,这将是索引0. – 2012-03-28 01:25:56

回答

0

您的代码是完全正确的,但您的头脑中有一个单一的错误。考虑一下,在初始化控件之后,您正在将项目加载到ComboBox中。此时控件没有项目,因此属性“文本”不会自动设置。

您必须在SelectedIndex(项目列表中项目的索引)和ComboBox中显示的Text(文本)之间有所不同。所以想想你应该在什么时候以及如何设置ComboBox的Text-property。

总是将Text-property设置为项目列表的第一个值,然后再对其进行更改。

问候,

+0

感谢您的回复!我在表单加载方法的底部添加了这一行(cboConversion.Text = conversionChoices [0,0] +“to”+ conversionChoices [0,1];),它现在正在工作。我感谢你不只是给我代码,而且还解释了为什么,因为我还在学习,这真的更有帮助。 – 2012-03-28 00:40:29

+0

你应该接受答案 – 2012-11-19 14:49:15

+0

嗨!如果我的答案解决了您的问题,请接受它;) – 2012-12-01 00:32:12

0

马里奥的回答也可以解释为:

把你的代码加载(例如:在显示事件)之后,以这种方式控制被初始化,并具有项目。

相关问题