当前位置: 移动技术网 > IT编程>开发语言>.net > C# listbox DataSource数据绑定--一年半以前的bug

C# listbox DataSource数据绑定--一年半以前的bug

2019年02月23日  | 移动技术网IT编程  | 我要评论

我结婚了 安敏捷,九阴九阳全文阅读,慈溪长途汽车站

listbox使用datasource进行数据绑定和删除,大家肯定都会,

写这个随笔只是因为。。。。这是一年半以前刚进公司的我遗留的bug,现在看看当时竟然没有解决 - -

现在写个测试程序,写个随笔记录一下,当时萌新的我。。。

首先声明了一个类,要绑定的类型。

//声明一个全局集合
public list<bindingtype> bi;
//声明一个绑定类型的类
public class bindingtype
{
    public string name { get; set; }//名称
    public datetime time { get; set; }//时间
}

然后两个方法,一个添加,一个删除。问题就出现在删除当中。

 private void button1_click(object sender, eventargs e)
        {
            //初始化添加数据
            bi = new list<bindingtype>()
            {
                new bindingtype { name=guid.newguid().tostring("n"),time=datetime.now},
                new bindingtype { name=guid.newguid().tostring("n"),time=datetime.now},
                new bindingtype { name=guid.newguid().tostring("n"),time=datetime.now},
                new bindingtype { name=guid.newguid().tostring("n"),time=datetime.now},
            };

            //绑定到listbox
            hashset<bindingtype> hs = new hashset<bindingtype>(bi);
            bindingsource bs = new bindingsource();
            bs.datasource = hs;
            listbox1.datasource = bs;
            listbox1.displaymember = "name";
        }

        private void button2_click(object sender, eventargs e)
        {
            //删除集合选中数据
            foreach (bindingtype item in listbox1.selecteditems)
            {
                bi.remove(item);
            }

            //重新绑定新的集合  如果此处bi这个集合数据为空就会出现显示错误
            hashset<bindingtype> hs = new hashset<bindingtype>(bi);
            bindingsource bs = new bindingsource();
            bs.datasource = hs;
            listbox1.datasource = bs;
            listbox1.displaymember = "name";
        }

 

左边是添加效果图,右边是全部删除之后会提示绑定的错误。

      

 

没有使用 items 进行数据绑定是因为需要取绑定中的数据。

当时记得弄了大半天都没有解决,最近刚好有个新的接口接入需要类似的功能,导致这个问题再次出现。。。

 想了一下使用 remove,clear是没办法删除的因为属于绑定数据,然后试试给他赋值一个新的 bindingsource。

            //删除集合选中数据
            foreach (bindingtype item in listbox1.selecteditems)
            {
                bi.remove(item);
            }

            if (bi.count < 1)//结合没有数据
            {
                //重新new
                bindingsource bs = new bindingsource();
                listbox1.datasource = bs;
            }
            else
            {
                //重新绑定新的集合  如果此处bi这个集合数据为空就会出现显示错误
                hashset<bindingtype> hs = new hashset<bindingtype>(bi);
                bindingsource bs = new bindingsource();
                bs.datasource = hs;
                listbox1.datasource = bs;
                listbox1.displaymember = "name";
            }

 

到此。。。算是解决了不会显示错误,然后说看看这个datasource是个什么东西,结果发现 “默认为null” 这几个字。。。。瞬间自己都笑了,

直接 listbox1.datasource = null; 

当时的我还真的萌新。。这么简单的问题我竟然没有解决。。。活到老,学到老。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网