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;
                }
            }
    
  • 相关阅读:
    摊还分析
    web端手机方向传感器闲谈
    研一一年论文总结(下)
    Jupyter自定义设置详解
    HAProxy实现动静分离和负载均衡
    欧拉项目 323题
    mysql基本操作
    以后的IT路还很长(1)
    【翻译】在Ext JS集成第三方库
    吴裕雄--天生自然JAVA SPRING框架开发学习笔记:Spring IoC容器BeanFactory和ApplicationContext
  • 原文地址:https://www.cnblogs.com/nutix/p/11323428.html
Copyright © 2011-2022 走看看