强制移除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;
            }
        }

猜你喜欢

转载自www.cnblogs.com/vitrox/p/11323428.html