How do I get the listbox to be sorted in ascending order?

0

Hello

My C # project has a listbox that lists numbers entered by the user. What I want to do is to constantly update these numbers in the listbox.

I tried to use the Sorted tool, but what happens is: link

In print: I entered with the values 1,2,3,4,5,6 and when I entered with the value 11, it appeared just below the 1.

Confirm Value Button Code:

if (tbNumero.Text == "")
        {
            MessageBox.Show("Não foi digitado nenhum número.", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else
        {
            try
            {
                lstRoll.Items.Add(Convert.ToDouble(tbNumero.Text));                                                          
                btnRemoveRoll.Enabled = true;
                btnResetAll.Enabled = true;

                tbNumero.Text = "";
                tbNumero.Focus();
                lstRoll.Sorted = true;
            }
            catch (Exception)
            {
                MessageBox.Show("Por favor, digite apenas numeros", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tbNumero.Text = "";
                tbNumero.Focus();
            }

        }

Resolved with this video: link

    
asked by anonymous 24.03.2018 / 01:39

1 answer

0

Even if you have converted the text to type Double , before adding the value to ListBox :

lstRoll.Items.Add(Convert.ToDouble(tbNumero.Text));

The classification in the control ListBox is always done alphabetically, treating the items as if they were String type:

  

ListBox.Sorted Property
link

You can then throw the list of values into an array, sort them there and return the sorted list, numerically, to ListBox :

// Cria um array de doubles com a mesma quantidade de itens que o ListBox.
double[] arrayNumerico = new double[lstRoll.Items.Count];
// Copia a lista de itens para o array de doubles.
((ICollection)lstRoll.Items).CopyTo(arrayNumerico, 0);
// Classifica o array de doubles, de forma numérica.
Array.Sort(arrayNumerico);
// Limpa o conteúdo do ListBox e adiciona os itens do array, classificados numericamente.
lstRoll.SetItemsCore(arrayNumerico);

EDIT:
I did not realize that the scope of the ListBox.SetItemsCore() method is Protected , so you will not be able to use it directly. In its place (the last line of the code) you can do so, then:

lstRoll.Items.Clear();
lstRoll.Items.AddRange((object[])arrayNumerico); 
    
24.03.2018 / 02:23