【问题标题】:Putting alternate elements of an array into a combobox将数组的备用元素放入组合框中
【发布时间】:2013-12-09 12:09:58
【问题描述】:

我在一个数组(statsname)中有一定数量的元素。

其实是这样的

x[1] A_NAME
x[2] A_CATEGORY
x[3] ANOTHER_NAME
x[4] A_CATEGORY

我想要组合框中的类别。 我做了

 int up =1; 
            foreach (string things in statsname)
            { 
                //if the stat name doesnot contains TIME
                //Only then we add it to the combobox.
                if ((Convert.ToString(things[up]) == "CurrentNumber") || (Convert.ToString(things[up]) == "TotalNumber"))
                {
                    tcomboBox1.Items.Add(things[up-1]);
                }
                up++;

                if (up != statsname.Count())
                {
                    tcomboBox1.Items.Add(things[up - 1]);
                }
            }

但是我得到一个错误提示

Array out of bound

为什么会这样? 我哪里做错了?

【问题讨论】:

  • 因为它不满足条件,并且您将索引增加到甚至没有落在数组大小中的程度。请使用断点调试。

标签: c# arrays loops foreach


【解决方案1】:

问题:您将characterString 合并,它永远不会变成true

解决方案:如果您只想将所有Categories 添加到array 中的odd 位置,例如1、3、5..等,

您可以从array 中取出奇数并将该值分配给combobox

编辑:如果您愿意,您可以从数组中获取偶数值并将该值分配给combobox

试试这个:

string [] statsname=new string[]  {"A_NAME1","Cat1","A_NAME2","Cat2","A_NAME3","Cat3","A_NAME4","Cat4"};
for(int i=0;i<statsname.Length;i++)
        {
         if(i%2==0)
           tcomboBox1.Items.Add(statsname[i]);
        }

【讨论】:

  • 我需要 0 ,2,4,6 位置的物品。如何获得?
【解决方案2】:

发生了IndexOutOfRangeException。这发生在使用数组类型的 C# 程序中。当语句尝试访问索引大于最大允许索引的元素时,通常会发生此异常。

for (int i = 0; i < type.Length; i++)
{
    form.comboBox1.Items.Add(type[i]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多