如何在用户输入文本后对组合框进行排序

时间:2015-06-25 17:37:31

标签: c# asp.net combobox

我有组合框,用户可以在其中输入文字或从列表中选择。当用户输入自己的文本,而不是显示在下拉列表的底部或顶部时,我希望它以正确的顺序显示。例如,如果用户键入24,我希望它在20到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();
        }
    }

2 个答案:

答案 0 :(得分:1)

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

如果您正在使用Win Forms,只需使用ComboBox.Sorted = true;

如果组合框中的数据来自列表形式,只需将OrderBy用于放置在ComboBox中的数据列表。 例如:

    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());

答案 1 :(得分:0)

我没有执行items.add()并将项目附加到列表的底部,而是将项目插入到正确的索引中。

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

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

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