Imagine that we have 10 Labels from up to down in a Form, that each of them contains a number.
How can I sort these Labels?, so that the greatest number go to the top of Labels and the smallest one go to the end?

Recommended Answers

All 2 Replies

Do you want to programmatically switch out their captions or move each label on the form?

You could use a listbox to do this, but assuming you have reason to not do this,
Create a label array

Label[] labels = {label1, label2 etc}
for(int x = 0; i < labels.Count(); x++)
{
    var changes = false;
    for (int i = 0; i < labels.Count() - 1 - x; i++)
    {
        if (Int.Parse(labels[i].Text) > Int.Parse(labels[i + 1].Text)
        {
            var x = labels[i].Top;
            labels[i].Top = label[i + 1].Top;
            labels[i + 1].Top = x;
            changes = true;
        }
    }
    if (changes == false)
        break;
}

I didn't write this in the compiler, so some parts may be wrong. Check it over. This is the bubble sort I have done in maths. The reason x is taken away each time is because the highest number sinks to the top every pass, so you don't need to compare it. The - 1 is because you cannot compare the last on its own.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.