码迷,mamicode.com
首页 > 其他好文 > 详细

关于ListBox的几个问题

时间:2014-11-05 14:27:48      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   for   sp   数据   

            Winfrom ListBox绑定数据源list界面不更新问题与绑定数据源不可CRUD问题

 

场景:获取一个listbox的选中项添加到另一个listbox中

 

解决方案-1:不要直接绑定DataSource 先把ListBox绑定到BindingSource bs中在绑定bs即可

 

代码案例:

    1-1:可更新全部添加

   

 private void btnAdd_Click(object sender, EventArgs e)

     {

     ListBox.SelectedObjectCollection selectObj = this.listLeft.SelectedItems;

foreach (DataRowView item in selectObj)

{

Sta sta = new Sta();

sta.STCD = int.Parse(item.Row.ItemArray[0].ToString());

sta.Name = item.Row.ItemArray[1].ToString();

list.Add(sta);

}

BindingSource bs = new BindingSource();

bs.DataSource = list;

this.listRight.DataSource = bs;

this.listRight.DisplayMember = "NAME";

this.listRight.ValueMember = "STCD";

     }

 

 

    1-2:更改后的 去掉重复项添加

 

  private void btnAdd_Click(object sender, EventArgs e)

{

ListBox.SelectedObjectCollection selectObj = this.listLeft.SelectedItems;

foreach (DataRowView item in selectObj)

{

bool b = true;

//要查看listright是否已经有了这一项,有就不添加

foreach (Model.Sta rightItem in this.listRight.Items)

{

if (rightItem.Name == item.Row.ItemArray[1].ToString())

{

b = false;

}

}

if (b)

{

Sta sta = new Sta();

sta.STCD = int.Parse(item.Row.ItemArray[0].ToString());

sta.Name = item.Row.ItemArray[1].ToString();

list.Add(sta);

}

 

 

}

BindingSource bs = new BindingSource();

bs.DataSource = list;

this.listRight.DataSource = bs;

this.listRight.DisplayMember = "NAME";

this.listRight.ValueMember = "STCD";

}

 

    1-3: 妈蛋 设置 DataSource 属性后无法修改项集合 只能绑定到list集合了,不知道有没有好办法解决

    ····换成list还是不行,根本原因就是不能用datasource去绑定

        只能直接添加item

    1-4 最终版本 0.0

   

 #region 添加右边listboxitems

ListBox.SelectedObjectCollection selectObj = this.listLeft.SelectedItems;

foreach (Model.Sta item in selectObj)

{

bool b = true;

//要查看listright是否已经有了这一项,有就不添加

foreach (Model.Sta rightItem in this.listRight.Items)

{

if (rightItem.Name == item.Name)

{

b = false;

}

}

if (b)

{

Sta sta = new Sta();

sta.STCD = item.STCD;

sta.Name = item.Name;

this.listRight.Items.Add(sta);

}

}

this.listRight.DisplayMember = "NAME";

this.listRight.ValueMember = "STCD";

#endregion

 

//删除左边已经添加的item

//1-2:把选中的item移除

int icount = listLeft.SelectedItems.Count;

for (int i = 0; i < icount; i++)

{

this.listLeft.Items.Remove(listLeft.SelectedItems[icount - 1 - i]);

}

 

关于ListBox的几个问题

标签:style   blog   io   color   ar   os   for   sp   数据   

原文地址:http://www.cnblogs.com/fucker/p/4076151.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!