您的位置:首页 > 其它

关于ListBox的几个问题

2014-11-05 13:33 204 查看

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]);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: