ArtisanSamosa
ArtisanSamosa

Reputation: 877

How do I sort a combobox after a user inputs text

I have combobox where users can input text or select from a list. When a user inputs their own text, instead it showing up at the bottom or top of the dropdown list, I want it to appear in the correct order. For example if a user types in 24 I want it to apear between 20 and 30.

private void LoadComboBox()
    {
        if (ddlTypeUnits.SelectedValue == "HP")
        {
            MotorSizeThreePhase[] motors = MotorSizeThreePhaseFactory.GetList(ActingMotorType, IsHPorBTU, IsAC, true, Common.GetConnectionString());

            cmbOutputRating.DataSource = motors;
            cmbOutputRating.DataTextField = "MotorSizeHP";
            cmbOutputRating.DataValueField = "MotorSizeHP";
            cmbOutputRating.DataBind();

        }

        ThreePhaseMotorLoad curLoad = (ThreePhaseMotorLoad)this.LoadObject;
        ListItem item = new ListItem(curLoad.Size.ToString()); //gets the stored size value
        if (!cmbOutputRating.Items.Contains(item))  //add the size value to the dropdown list
        {
            cmbOutputRating.DataBind();
            cmbOutputRating.Items.Add(item);
            cmbOutputRating.Text = curLoad.Size.ToString();
        }
    }

Upvotes: 1

Views: 899

Answers (2)

ArtisanSamosa
ArtisanSamosa

Reputation: 877

Instead of doing items.add() and appending the item to the bottom of the list, I inserted the item into the correct index.

            int newItemIndex = 0;
            foreach (ListItem li in cmbOutputRating.Items)
            {

                if (Convert.ToDouble(li.Value) < curLoad.Size)
                {
                    newItemIndex++;
                }
            }

            cmbOutputRating.Items.Insert(newItemIndex, curLoad.Size.ToString());

Upvotes: 0

Miroslav Bihari
Miroslav Bihari

Reputation: 31

C# - is it possible to arrange ComboBox Items from a to z?

If you're using Win Forms, just use ComboBox.Sorted = true;

If the data in your combo box comes from in a form of a list, just use OrderBy to the List of data you are going to put in the ComboBox before putting it. example:

    List<string> a = new List<string>()
    {
        "q",
        "w",
        "e",
        "r",
        "t",
        "y",
        "u",
        "i",
        "o",
        "p",
        "a",
        "s",
        "d",
        "f",
        "g",
        "h",
        "j",
        "k",
        "l",
        "z",
        "x",
        "c",
        "v",
        "b",
        "n",
        "m",
    };

    comboBox1.Items.AddRange(a.OrderBy(c => c).ToArray());

Upvotes: 1

Related Questions