首页 > 代码库 > 关于ListBox的几个问题

关于ListBox的几个问题

            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 添加右边listboxitemsListBox.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的几个问题