System.IndexOutOfRangeException c#

时间:2013-02-22 14:54:48

标签: c# string

不知何故,这似乎在几年前工作;) 或者我错过了什么?帮助将不胜感激 提前谢谢。

else if (recStatus == 3)         
{
            ((TextBox)rref[1]).Text = read;

            //string readData = read;
            string[] readData = read.Split(new Char[] { ',' });


            //string[] readdata = read.Split(',');
            txtType.Text = readData[0];
            txtSerno.Text = readData[1]
            txtFirmware.Text = readData[2] + "." + readData[3];
}

2 个答案:

答案 0 :(得分:1)

此代码中的System.IndexOutOfRangeException意味着readData的值小于4,

你可以通过

知道元素的数量
string[] readData = read.Split(new Char[] { ',' });
MessageBox.Show(readData.Length.ToString()); //you will found it less then 4

答案 1 :(得分:0)

我只是运行你的示例并且在控制台应用程序中没有错误(可能是因为你传递的文本放了一个调试器,看看实际文本是什么((TextBox)rref [1])。 ):

class Program
    {
        static void Main(string[] args)
        {
            string read = "A401,192,2,8" ;

            string[] readData = read.Split(new Char[] { ',' });


            //string[] readdata = read.Split(',');
            string a = readData[0];
            string b = readData[1] + "." + readData[2];
            string c = readData[3];

            Console.WriteLine(a + b + c);
        }
    }

结果:

A401192.28
Press any key to continue . . .