C# Winform ComboBox模糊查询实现

 

        public static void FuzzyMatch(this ComboBox cmb, IEnumerable<string> list) {
            var templist = list.Where(x => x.Contains(cmb.Text.Trim())).ToArray();
            cmb.Items.Clear();
            cmb.Items.AddRange(templist);
            if (cmb.Items.Count == 0) cmb.Items.Add(""); 
            //至少要有一项,以避免dropdown的时候ArgumentOutOfRangeException  InvalidArgument=“0”的值对于“index”无效。
            cmb.DroppedDown = false;
            cmb.DroppedDown = true;
            cmb.Select(cmb.Text.Length, 0);
            cmb.FindForm().Cursor= Cursor.Current;  //避免兴标消失
        }

  频繁dropdown,对于低性能电脑体验很差,做如下优化:

public static void FuzzyMatch(this ComboBox cmb, IEnumerable<string> list) {
    var templist = list.Where(x => x.Contains(cmb.Text.Trim())).ToArray();
    cmb.Items.Clear();
    cmb.Items.AddRange(templist);
    if (cmb.Items.Count == 0) cmb.Items.Add("");
    //至少要有一项,以避免dropdown的时候ArgumentOutOfRangeException  InvalidArgument=“0”的值对于“index”无效。
    cmb.Select(cmb.Text.Length, 0);
    cmb.FindForm().Cursor = Cursor.Current;  //避免光标消失
    if (cmb.MaxDropDownItems < 20) cmb.MaxDropDownItems = 20;
    if (!cmb.DroppedDown)cmb.DroppedDown = true;       
}

 

posted @ 2024-08-15 18:12  enif  阅读(245)  评论(0编辑  收藏  举报
豫ICP备2021034901号