zoukankan      html  css  js  c++  java
  • 强制移除ComboBox或ListBox中的项,即使是用 DataSource 属性初始化的项集合

            /// <summary>
            /// 强制移除列表控件中的指定项。
            /// 如果列表控件的项,是由 DataSource 属性增加的。
            /// </summary>
            /// <param name="lc">要操作的列表控件</param>
            /// <param name="indexToRemove">
            /// 要移除的项序数,从0开始。
            /// 如果不提供,将会使用 SelectedIndex 属性来填充
            /// </param>
            public static void RemoveItem(ListControl lc, int indexToRemove = -1)
            {
                int iSelected = -1;
                string mDisplay = null;
                object ds = null;
    
                IList items = null;
                if(lc is ComboBox)
                {
                    items = (lc as ComboBox).Items;
                }
                if(lc is ListBox)
                {
                    items = (lc as ListBox).Items;
                }
                if(indexToRemove == -1)
                {
                    indexToRemove = lc.SelectedIndex;
                }
    
                if (indexToRemove != -1)
                {
                    iSelected = lc.SelectedIndex;
                    mDisplay = lc.DisplayMember;
    
                    if (lc.DataSource == null)
                    {
                        items.RemoveAt(indexToRemove);
                        MessageBox.Show(lc.SelectedIndex.ToString());
                    }
                    else
                    {
                        ds = lc.DataSource;
                        //此操作,会清空 items
                        lc.DataSource = null;
                        //ListBox/ComboBox 的 Items 是 IList 类型或数组,而数组也实现了 IList 接口
                        IList lst = ds as IList;
                        for(int i = 0; i < lst.Count; i++)
                        {
                            if(i != indexToRemove) 
                                items.Add(lst[i]);
                        }
                    }
                }
                if (ds != null)
                {
                    if (lc is ComboBox)
                    {
                        ComboBox cbb = lc as ComboBox;
                        cbb.DataSource = items;
                        cbb.SelectedIndex = iSelected;
                    }
                    if (lc is ListBox)
                    {
                        ListBox lb = lc as ListBox;
                        lb.DataSource = items;
                        lb.SelectedIndex = iSelected;
                    }
                    lc.DisplayMember = mDisplay;
                }
            }
    
  • 相关阅读:
    prim 堆优化+ kruskal 按秩优化
    poj 2679 Adventurous Driving(SPFA 负环)
    poj 1125 Stockbroker Grapevine (dij优化 0ms)
    codevs 4909 寂寞的堆(写的好丑0.0)
    noi 7221 拯救公主 (状态压缩+bfs)
    codevs2059逃出克隆岛(传送门bfs)
    HUD3336
    poj 3974 Palindrome
    疑难杂症
    正则表达 比较两个浮点数
  • 原文地址:https://www.cnblogs.com/nutix/p/11323428.html
Copyright © 2011-2022 走看看