简体   繁体   中英

Unable to cast object type System.Decimal to type System.String from sorting listbox

So im trying to run a windows form which you add a number from a numericUpDown box (from the WindowsForm) and it puts it in the listbox (which my code does fine). Example of what it looks like in the list box:

7 5 10 1

and when you click sort it should produce in the order of:

1 5 7 10

When I run my code and click the sort button (button1) to sort the ints in the list box I get:

"System.InvalidException: "Unable to cast object of type 'System.Decimal' to type 'System.String'.

Im not sure what this means....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ListBoxSorter
{
    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //int num = (int)listBox1.Items[0];
            //listBox1.Items.Add(num);


        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            //int number = (int)numericUpDown1.Value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //listBox1.Items.Sort(numericUpDown1.Value);

            List<int> ListB = new List<int>();

            foreach (string x in listBox1.Items)
            {
                ListB.Add(Convert.ToInt32(x));
            }
            ListB.Sort();
        }



        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(numericUpDown1.Value);
        }
    }
}

Try this: (not compiled or debugged)

private void button1_Click(object sender, EventArgs e)
{
    List<int> ListB = new List<int>();

    foreach (string x in listBox1.Items)
    {
        ListB.Add(Convert.ToInt32(x));
    }

    ListB.Sort();

    listBox1.Items.Clear() //important!

    foreach (int x in ListB)
    {
        listBox1.Items.Add(x.ToString());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM