Home > Software engineering >  'Failed to cast object' System.String [] 'to type' System.IConvertible '.&#
'Failed to cast object' System.String [] 'to type' System.IConvertible '.&#

Time:12-12

I need to read the numbers in the txt file in listBox and convert it to numbers. But I get an error ---> 'Failed to cast object' System.String [] 'to type' System.IConvertible '.' what can I do? I am using C # windows application. Thanks.

var lines = File.ReadAllLines("C:\\Numbers\\numbers.txt");

        for (int i = 0; i < lines.Length; i  )
        {
            var fields = lines[i].Split(' ');
            Convert.ToInt32(fields);
            listBox1.Items.Add(fields);
        }

CodePudding user response:

Split() gives you an array. You can't convert a whole array into numbers. Use a loop to iterate through the fields and add them to the listbox.

Also, you need to use the return value of Convert.ToInt32() (actually, when you assign it to a listbox, it will be converted to a string again).

CodePudding user response:

you don't need to convert string to int in order to add it to listbox items and you doing it wrong way. Just remove this line from your code

 Convert.ToInt32(fields);

and your code should be

List<string> items= new List<string>();
for (int i = 0; i < lines.Length; i  )
{
 var fields = lines[i].Split(' ');
 items.AddRange(fields);
}
ListBox1.Items.AddRange(items);
  • Related